简体   繁体   中英

when socketChannel.read(BUFFER) will return 0

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 ie Suppose client wrote: stack overflow , is it possible that in the server count will be 0 after reading stack ie half of the message that the client has sent (think that the message can be of 1MB size)?

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 eg ~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. eg if 1500 bytes is waiting and you read just 8 bytes, you get part of that packet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM