简体   繁体   中英

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).

I configured the SocketChannel as blocking mode .

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.

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.

looks like reading thread is blocking writing thread

AFAIK, TCP connections can offer bi-direction operations at the same time. Can anyone help to explain this?

As explained in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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