我对 java.net 中 Socket 的 setReceiveBufferSize()
的使用感到困惑。
从 API 中,我知道设置套接字的接收缓冲区大小定义(或提示)套接字一次可以接收的数据限制。然而,每次我尝试从套接字的输入流中读取时,我发现它可以存储比我用 setReceiveBufferSize() 设置的更多的数据。
考虑以下代码:
InputStream input_stream = socket.getInputStream();
socket.setReceiveBufferSize(1024);
byte[] byte_array = new byte[4096];
input_stream.read(byte_array);
每次我从input_stream
读取时,我都测试过我一次实际上可以读取超过1024字节(并填充4096字节的数组),只要发送方已经发送不止这么多数据。
谁能解释一下为什么会这样?我只是错过了什么吗?谢谢。
最佳答案
From the API, I know that setting the receive buffer size for the socket defines (or gives a hint to) the data limit that the socket can receive at a time.
不,它没有。它向 TCP 提供有关总接收缓冲区大小的提示,这反过来会影响可以通告的最大接收窗口。 “一次接收”与它没有任何关系。
However, every time I try to read from the socket's input stream, I've found out that it can store more than what I set with setReceiveBufferSize().
TCP 可以自由地向上或向下调整提示。在这种情况下,1024 是一个小得可笑的大小,任何实现都会增加到至少 8192。您可以通过 getReceiveBufferSize() 找出实际使用了多少 TCP。
关于java - socket.setReceiveBufferSize()的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24712577/