[英]Java - Different socket for same TCP IP
I want to create different thread for read and write method by using socket. 我想通过使用套接字为读写方法创建不同的线程。 I wonder should I use different socket or same socket to share for both thread?
我想知道我应该使用不同的套接字还是相同的套接字共享两个线程?
If you're reading and writing to and from the same device/object, i'd use the same thread. 如果您要在同一设备/对象上读写,那么我将使用同一线程。 This way you don't have it trying to read something when you haven't written to it yet.
这样,当您尚未写入内容时,您就不会尝试读取内容。 Doing multiple threads might cause a multitude of errors if you're not careful, such as nulls.
如果不小心,执行多个线程可能会导致多种错误,例如null。
You can use the same socket to both read and write. 您可以使用同一套接字读取和写入。 Of course one of the 2 endpoints must open a server socket.
当然,两个端点之一必须打开服务器套接字。 Then you can have 1 thread blocked waiting for input data while another thread could output data when needed
然后,您可以阻止一个线程等待输入数据,而另一个线程可以在需要时输出数据
1. Create One socket object . 1.创建一个套接字对象 。
2. Use any nos of threads to access this object, but do keep enough care to make the write and read operations Thread-Safe
. 2.使用任意数量的线程来访问该对象,但要保持足够的小心,以使写入和读取操作成为
Thread-Safe
。
3. Try using the ServerChannel
and ServerSocketChannel
from java.util.nio
package, which is Asynchronous . 3.尝试使用
java.util.nio
包中的ServerChannel
和ServerSocketChannel
,它是Asynchronous 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.