gpt4 book ai didi

Java SocketChannel 读取时写入被阻止

转载 作者:行者123 更新时间:2023-12-02 13:11:03 27 4
gpt4 key购买 nike

我尝试在两个不同的线程(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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com