简体   繁体   English

没有NIO的全双工TCP连接是不可能的?

[英]Full duplex TCP connection without NIO impossible?

I have two separate java processes communicating over a single TCP connection. 我有两个单独的Java进程通过单个TCP连接进行通信。 The protocol is not a simple synchronous request/response one like HTTP. 该协议不是类似于HTTP的简单同步请求/响应。 Both sides may independently initiate requests and send data. 双方均可独立发起请求并发送数据。 I want to implement this using threads and blocking sockets, avoiding NIO. 我想使用线程和阻塞套接字来实现这一点,避免使用NIO。 But is this even possible? 但这有可能吗?

Java sockets (java.net.Socket) are not threadsafe, so i'm not allowed to read from the socket in one thread while simultaneously writing to it in another thread. Java套接字(java.net.Socket)不是线程安全的,因此不允许我在一个线程中从套接字读取数据,而同时在另一个线程中对其进行写入。 (Is this true?) This restriction obviously leads to the possibility of deadlock, when both sides are blocked writing to the socket. (这是真的吗?)当双方都被阻止写入套接字时,此限制显然会导致死锁。

It follows that certain protocols on top of TCP can't be implemented in java without using NIO, or am i missing a point? 因此,如果不使用NIO,就无法在Java中实现TCP之上的某些协议,否则我会遗漏一点吗?

Thank you. 谢谢。

Full duplex communication is certainly possible. 全双工通信当然是可能的。 Without NIO, you'll need a thread to read from the socket (and perform the requested processing). 如果没有NIO,则需要一个线程从套接字读取(并执行请求的处理)。 Meanwhile, another thread can be writing to the same socket. 同时,另一个线程可以写入同一套接字。

If you can point out some documentation that suggests that sockets are not full duplex, I'll try to clarify it. 如果您可以指出一些说明套接字不是全双工的文档,那么我将尝试对其进行说明。

I don't know where you've read that Java sockets are generally thread-unsafe. 我不知道您在哪里读到Java套接字通常是线程不安全的。 You can't have multiple threads simultaneously writing or reading from the socket's streams, but there's no reason why you can't have on thread writing to the socket's OutputStream and another thread reading from the socket's InputStream. 您不能同时有多个线程从套接字的流中写入或读取,但是没有理由不能对线程写入套接字的OutputStream和从线程的InputStream读取另一个线程。

Sockets are thread safe so there's no problem with using multiple threads, one for reading and one for writing. 套接字是线程安全的,因此使用多个线程(一个用于读取,一个用于写入)没有问题。 On the other hand if you want to avoid multiple threads then you need to perform polling on the socket input stream to see if there's incoming data on a regular basis while you're performing whatever outbound operations you have. 另一方面,如果要避免使用多个线程,则需要在执行任何出站操作时对套接字输入流执行轮询,以查看是否定期有传入数据。

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

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