简体   繁体   English

Java中的非阻塞套接字写入与阻塞套接字写入相比

[英]Non-blocking socket writes in Java versus blocking socket writes

Why would someone prefer blocking writes over non-blocking writes? 为什么有人更喜欢阻止写入非阻塞写入? My understanding is that you would only want blocking write if you want to make sure the other side got the TCP packet once the write method returned, but I am not even sure that's possible. 我的理解是,如果你想确保另一方在写入方法返回后得到TCP数据包,你只想要阻塞写入,但我甚至不确定是否可能。 You would have to flush and flush would have to flush the underlying operating system write socket buffer . 你必须刷新和刷新必须刷新底层操作系统写入套接字缓冲区 So is there any disadvantage of non-blocking socket writes? 那么非阻塞套接字写入有什么缺点吗? Does having a large underlying write socket buffer a bad idea in terms of performance? 有一个大的底层写入套接字缓冲在性能方面是一个坏主意吗? My understanding is that the smaller the underlying socket write buffer the more likely you will hit slow/buggy client and have to drop/queue packets in the application level while the underlying socket buffer is full and isWritable() is returning false. 我的理解是,底层套接字写缓冲区越小,你就越有可能遇到慢/错误的客户端,并且在底层套接字缓冲区已满并且isWritable()返回false时,必须在应用程序级别中丢弃/排队数据包。

My understanding is that you would only want blocking write if you want to make sure the other side got the TCP packet once the write method returned 我的理解是,如果你想确保一旦返回write方法,另一方得到TCP数据包,你只想要阻塞写

Your understanding is incorrect. 你的理解是不正确的。 It doesn't ensure that. 它无法确保这一点。

Blocking writes block until all the data has been transferred to the socket send buffer, from where it is transferred asynchronously to the network. 阻塞写入阻塞,直到所有数据都已传输到套接字发送缓冲区,从那里异步传输到网络。 If the reader is slow, his socket receive buffer will fill up, which will eventually cause your socket send buffer to fill up, which will cause a blocking write to block, blocking the whole thread. 如果读取器很慢,他的套接字接收缓冲区将填满,这最终会导致套接字发送缓冲区填满,这将导致阻塞写入阻塞,阻塞整个线程。 Non-blocking I/O gives you a way to detect and handle that situation. 非阻塞I / O为您提供了一种检测和处理这种情况的方法。

The problem with non blocking writes is that you may not have anything useful to do if the write is incomplete. 非阻塞写入的问题在于,如果写入不完整,您可能没有任何有用的操作。 You can end up with loops like 你最终可能会像

// non-blocking write
while(bb.remaining() > 0) sc.write(bb);

OR 要么

// blocking write
sc.write(bb);

The first can burn CPU and the second might be more desirable. 第一个可以燃烧CPU,第二个可能更合适。

The big problem is reads. 最大的问题是读取。 Once you decide whether you want blocking or non-blocking reads, your writes have to be the same. 一旦确定是要阻塞还是非阻塞读取,您的写入必须相同。 Unfortunately there is no way to make them different. 不幸的是,没有办法让它们与众不同。 If you want non-blocking reads, you have to have non-blocking writes. 如果您想要非阻塞读取,则必须进行非阻塞写入。

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

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