简体   繁体   中英

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

I am a new java socket developer. 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.

You create a Selector and register the 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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