Java 套接字是否支持全双工?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6265731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Do Java sockets support full duplex?
提问by Tony the Pony
Is it possible to have one thread write to the OutputStream
of a Java Socket
, while another reads from the socket's InputStream
, without the threads having to synchronize on the socket?
是否可以让一个线程写入OutputStream
Java 的Socket
,而另一个InputStream
线程读取套接字的,而线程不必在套接字上同步?
采纳答案by jefflunt
Sure. The exact situation you're describing shouldn't be a problem (reading and writing simultaneously).
当然。您所描述的确切情况应该不是问题(同时阅读和写作)。
Generally, the reading thread will block if there's nothing to read, and might timeout on the read operation if you've got a timeout specified.
通常,如果没有可读取的内容,读取线程将阻塞,并且如果您指定了超时,则读取操作可能会超时。
Since the input stream and the output stream are separate objects within the Socket, the only thing you might concern yourself with is, what happens if you had 2 threads trying to read or write (two threads, same input/output stream) at the same time? The read/write methods of the InputStream/OutputStream classes are not synchronized. It is possible, however, that if you're using a sub-class of InputStream/OutputStream, that the reading/writing methods you're calling are synchronized. You can check the javadoc for whatever class/methods you're calling, and find that out pretty quick.
由于输入流和输出流是 Socket 中的独立对象,您可能唯一关心的是,如果您有 2 个线程试图同时读取或写入(两个线程,相同的输入/输出流)会发生什么时间?InputStream/OutputStream 类的读/写方法不同步。但是,如果您使用 InputStream/OutputStream 的子类,则您调用的读/写方法可能是同步的。您可以检查 javadoc 以了解您正在调用的任何类/方法,并很快找到它。
回答by Paul Cager
Yes, that's safe.
是的,那很安全。
If you wanted more than one thread reading from the InputStream you would have to be more careful (assuming you are reading more than one byte at a time).
如果您希望从 InputStream 读取多个线程,则必须更加小心(假设您一次读取多个字节)。