Search code examples
javanioserversocket

Why we need Java NIO Selector?


If we are creating a online-chat sever, i think we should only need a single ServerSocketChannel, isn't it ?

If we get only one ServerSocketChannel, why we need a Selector ?

Could anyone gives me a real project example needs to use Selector ?

Thanks !


Solution

  • When you accept() on a ServerSocketChannel, what you get back is a new SocketChannel which you then read() and write() to communicate to that client.

    Your selection code would typically select(), then iterate through the selected keys, accepting any key that isAcceptable() (thus opening a new channel), but then also reading and writing any key (presumably one of your accepted client channels) that isReadable() or isWritable().