Arvanem
Arvanem

Reputation: 1053

In Java NIO, is a selector useful for a client SocketChannel?

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?

Upvotes: 10

Views: 4103

Answers (2)

user207421
user207421

Reputation: 311031

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.

Upvotes: 8

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

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.

Upvotes: 7

Related Questions