[英]when socketChannel.read(BUFFER) will return 0
I have a server which reads from the SocketChannel
like below: 我有一个从
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();
}
}
And below is the client where client writes to the SocketChannel
: 下面是客户端向
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: 所以我的问题是:
count
value will be 0 ( while ((count = socketChannel.read(BUFFER)) > 0)
)? count
数值将为0( while ((count = socketChannel.read(BUFFER)) > 0)
)? 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)? count
将为0,即假设客户端编写了: stack overflow
,读取stack
之后,服务器的count
为0,即消息的一半,该count
是否为0?客户端已发送(认为邮件可以为1MB大小)? When using blocking mode, you will always get at least 1 byte. 使用阻止模式时,您将始终获得至少1个字节。 Note: you might only get 1 byte, it doesn't read "messages".
注意:您可能只会得到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. 当使用非阻塞模式时,实际上大多数时候没有数据包等待您时,您将获得0。
In TCP, data is sent in packets, not messages. 在TCP中,数据以数据包而不是消息的形式发送。 This means if you send 1 MB, most likely it will be broken into packets of your MTU size eg ~1500 bytes.
这意味着,如果您发送1 MB,则很有可能会将其分解为MTU大小的数据包,例如〜1500字节。 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.
例如,如果正在等待1500个字节,而您仅读取8个字节,则将获得该数据包的一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.