简体   繁体   English

Java中的阻塞套接字写入和非阻塞套接字写入有什么区别?

[英]What is the difference between a blocking socket write and a non-blocking socket write in Java?

The difference between non-blocking reads and blocking reads is obvious, but I am confused about writes. 非阻塞读取和阻塞读取之间的区别是显而易见的,但我对写入感到困惑。 I understand that a non-blocking write never blocks (duh!). 我知道非阻塞写永远不会阻塞(呃!)。 If the underlying socket buffer is full, bytes are simply not written to it. 如果底层套接字缓冲区已满,则不会向其写入字节。 That's why it is important to check how many bytes were written when you call channel.write. 这就是为什么在调用channel.write时检查写入了多少字节很重要的原因。

Now how about blocking writes ? 现在阻止写入怎么样? When does it block? 什么时候阻止? When you call flush? 当你打电话给同花? When you call write on its OutputStream? 当你在OutputStream上调用write时? Does it block until there is space in the underlying write socket buffer? 它是否会阻塞,直到底层写入套接字缓冲区中有空间? Or does it throw an exception if it cannot write? 或者,如果它不能写,它会抛出异常吗?

是的,它会阻塞,直到底层OS插槽发送缓冲区中有足够的空间来复制你的字节。当你将数据放入与套接字关联的Java OutputStream时,或者当你调用flush() ,可能会发生这种情况,无论哪个调用实际write(2)系统调用。

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

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