简体   繁体   English

Java SocketChannel写入在读取时被阻止

[英]Java SocketChannel write blocked while reading

I am trying to use SocketChannel.write and SocketChannel.read at the same time in two different threads (Android API Level 25). 我试图在两个不同的线程(Android API 25级)中同时使用SocketChannel.writeSocketChannel.read

I configured the SocketChannel as blocking mode . 我将SocketChannel配置为阻止模式

For reading, I created an endless loop to read everything from server: 为了阅读,我创建了一个无限循环来读取服务器中的所有内容:

// 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;
    }
}

And for writing, I write data each 10 seconds. 对于写入,我每10秒写入一次数据。

The problem is, I found that sometimes the writing operations were blocked while reading. 问题是,我发现有时写入操作在读取时被阻塞。

But if I make the reading thread sleep for a short period in each loop, eg 100ms, this problem won't appear anymore. 但是,如果我使读取线程在每个循环中短暂睡眠(例如100ms),则此问题将不再出现。

looks like reading thread is blocking writing thread 看起来读线程正在阻止写线程

AFAIK, TCP connections can offer bi-direction operations at the same time. AFAIK,TCP连接可以同时提供双向操作。 Can anyone help to explain this? 有人可以帮忙解释一下吗?

As explained in TCP Wikipedia - Flow Control : TCP Wikipedia-流控制中所述

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. TCP使用端到端流控制协议来避免发送方发送数据的速度过快,以至于TCP接收方无法可靠地接收和处理数据。 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. 例如,如果PC将数据发送到正在缓慢处理接收到的数据的智能手机,则智能手机必须调节数据流,以免被淹没。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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