9
votes

In Java NIO, it is easily understandable why a ServerSocketChannel must have a selector. The selector can check from among several client channels which is ready for I/O operations.

However, in some commentary I have read on the web, the selector mechanism is applied to the client SocketChannel. I don't understand why a selector is of use to a client. Can anyone explain why it is of use in the usual circumstance where there is only one server?

2
For example, tutorials.jenkov.com/java-nio/socket-channel.html at the bottom of the page makes the recommendation for selectors and SocketChannels.Arvanem
But he doesn't recommend any of it for clients. There's a lot of bad advice in that tutorial: looping in non-blocking mode for example. Find a better one.user207421

2 Answers

7
votes

Unless you're connecting to hundreds of servers, it is difficult to see the point of non-blocking NIO in a client at all. But if you're using non-blocking NIO, you definitely have to use a Selector, otherwise you can't know when to read the channel, or when it becomes writable again after an incomplete write.

6
votes

Selectors let you service concurrent communication across multiple channels using a single thread. It may be useful on a client when you must communicate with several servers concurrently, or when you communicate with peer computers in the role of a client, such as when reading a torrent.