Java SocketChannel 读取时写入被阻止

标签 java sockets socketchannel

我尝试在两个不同的线程(Android API 级别 25)中同时使用 SocketChannel.writeSocketChannel.read

我将 SocketChannel 配置为阻塞模式

为了阅读,我创建了一个无限循环来从服务器读取所有内容:

// Make socketChannel.read() return after 500ms at most
socketChannel.socket().setSoTimeout(500);
while(!SHUTDOWN) {
    int read = socketChannel.read(buffer);
    if(read > 0 ){
      // Do something nice
      break;
    }
}

对于写入,我每 10 秒写入一次数据。

问题是,我发现有时写入操作在读取时会被阻塞。

但是如果我让读取线程在每个循环中 hibernate 一小段时间,例如100ms,这个问题就不会再出现了。

看起来读取线程正在阻塞写入线程

据我所知,TCP 连接可以同时提供双向操作。谁能帮忙解释一下吗?

最佳答案

TCP Wikipedia - Flow Control 中所述:

TCP uses an end-to-end flow control protocol to avoid having the sender send data too fast for the TCP receiver to receive and process it reliably. Having a mechanism for flow control is essential in an environment where machines of diverse network speeds communicate. For example, if a PC sends data to a smartphone that is slowly processing received data, the smartphone must regulate the data flow so as not to be overwhelmed.

关于Java SocketChannel 读取时写入被阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43961714/

相关文章:

java:读写操作上的单个套接字。全双工

java - SocketChannel 的超时不起作用

java - 确定夏令时的小时数

java - 吉利德 GWT 与 playframework

WebSocketException : Connection to was not upgraded to websocket 上的 Flutter Socket io 错误

objective-c - 简单的 OS X TCP 转发服务器/服务

c - 为 Windows CE 移植 setsockopt() 和 RCVTIMEO

java - 在 Java 游戏中渲染比更新更快有什么好处?

java - 使用一个 Spring 表单绑定(bind) 2 个对象