I’m using this kind of code for my TCP/IP connection:
sock = new Socket(host, port);
sock.setKeepAlive(true);
din = new DataInputStream(sock.getInputStream());
dout = new DataOutputStream(sock.getOutputStream());
Then, in separate thread I’m checking din.available() bytes to see if there are some incoming packets to read.
The problem is, that if a packet bigger than 2048 bytes arrives, the din.available() returns 2048 anyway. Just like there was a 2048 internal buffer. I can’t read those 2048 bytes when I know it’s not the full packet my application is waiting for. If I don’t read it however – it’ll all stuck at 2048 bytes and never receive more.
Can I enlarge the buffer size of DataInputStream somehow? Socket receive buffer is 16384 as returned by sock.getReceiveBufferSize() so it’s not the socket limiting me to 2048 bytes.
If there is no way to increase the DataInputStream buffer size – I guess the only way is to declare my own buffer and read everything from DataInputStream to that buffer?
Regards
I’m going to make an assumption about what you’re calling a “packet”. I am going to assume that your “packet” is some unit of work being passed to your server. Ethernet TCP packets are limited to 1536 bytes. No matter what size writes the peer is performing.
So, you cannot expect to atomically read a full unit of work every time. It just won’t happen. What you are writing will need to identify how large it is. This can be done by passing a value up front that tells the server how much data it should expect.
Given that, an approach would be to have a thread do a blocking read on
din. Just process data as it becomes available until you have a complete packet. Then pass the packet to another thread to process the packet itself. (See ArrayBlockingQueue.)You socket reader thread will process data at whatever rate and granularity it arrives. The packet processor thread always works in terms of complete packets.