1

我有一个从下面读取的服务器SocketChannel

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();
        }
    }

下面是客户端写入的客户端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);
        }
    }

所以我的问题:

  • 当恰好在服务器代码中,该count值将是 0 ( while ((count = socketChannel.read(BUFFER)) > 0))?
  • count如果服务器已经读取了客户端发送的消息的一半,即假设客户端写道: stack overflow,服务器中是否有可能在count读取stack客户端发送的消息的一半后为0(认为消息可以是 1MB 大小)?
4

1 回答 1

1

使用阻塞模式时,您将始终获得至少 1 个字节。注意:您可能只会得到 1 个字节,它不会读取“消息”。

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.

于 2014-01-01T11:49:00.663 回答