Question

I have a server which reads from the SocketChannel like below:

private void readDataFromSocket(SocketChannel socketChannel) throws IOException {            
        BUFFER.clear();
        int count = 0;
        while ((count = socketChannel.read(BUFFER)) > 0) {
            BUFFER.flip();
            int limit = BUFFER.limit();
            while (limit > 0) {
                System.out.print((char) BUFFER.get());
                limit--;
            }                
        }            
        if (count < 0) {
            System.out.println("closing the socket!!!");
            socketChannel.close();
        }
    }

And below is the client where client writes to the SocketChannel:

private void write(String str, SocketChannel channel) throws IOException{
        byte[] b = str.getBytes();
        buffer.clear();
        buffer.put(b);
        buffer.flip();
        while(buffer.hasRemaining()){
            channel.write(buffer);
        }
    }

So my question:

  • when exactly in the server code the count value will be 0 ( while ((count = socketChannel.read(BUFFER)) > 0))?
  • is it possible that the count will be 0 if the server has read half of the message that client has sent i.e. Suppose client wrote: stack overflow, is it possible that in the server count will be 0 after reading stack i.e. half of the message that the client has sent (think that the message can be of 1MB size)?
Was it helpful?

Solution

When using blocking mode, you will always get at least 1 byte. Note: you might only get 1 byte, it doesn't read "messages".

When using non-blocking mode, you will get 0 most of the time, in fact whenever there is not a packet waiting for you.

In TCP, data is sent in packets, not messages. This means if you send 1 MB, most likely it will be broken into packets of your MTU size e.g. ~1500 bytes. If you read this socket, you will most likely see blocks of this size or a multiple if multiple packets came in since the last read. You will never see part of a packet, unless you read less than the available data. e.g. if 1500 bytes is waiting and you read just 8 bytes, you get part of that packet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top