简体   繁体   English

Java:多个套接字在单个线程中发送和接收维护

[英]Java: Multiple sockets send and receive maintain in a single thread

I am a new java socket developer. 我是一名新的Java套接字开发人员。 In my solution has three sockets for sending and receiving. 在我的解决方案中,有三个用于发送和接收的套接字。 I want to receive three socket's data in a single thread. 我想在一个线程中接收三个套接字的数据。 For this reason, how i get notification which socket get data from remote. 因此,我如何获得通知,通知哪个套接字从远程获取数据。

Handling multiple streams (those of the sockets) within a single thread is possible. 可以在单个线程中处理多个流(套接字的那些流)。 It requires the use of socket channels (from java.nio.channels) and of a (single) Selector. 它要求使用套接字通道(来自java.nio.channels)和一个(单个) Selector.

You create a Selector and register the SocketChannels. 您创建一个选择器并注册 SocketChannels.

To learn about any new possibility for an i/o operation, you call the Selector 's select() method, which returns whenever one of the channels is ready for reading, writing or accepting. 要了解进行I / O操作的任何新可能性,请调用Selectorselect()方法,只要其中一个通道可以读取,写入或接受,该方法就会返回。 You'll have to learn the ready channel (ie, obtain its "key"), and call its appropriate data transfer method. 您将必须学习就绪通道(即获取其“键”),并调用其适当的数据传输方法。

There is some sample code to be found on the net. 在网上可以找到一些示例代码。

PS: It might be easier to use threads. PS:使用线程可能会更容易。

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

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