I am trying to understand SocketChannels, and NIO in general. I know how to work with regular sockets and how to make a simple thread-per-client server (using the regular blocking sockets).
So my questions:
A selectable channel for stream-oriented connecting sockets.
. What does that mean?I have read the also this documentation, but somehow I am not getting it...
A Socket
is a blocking input/output device. It makes the Thread
that is using it to block on reads and potentially also block on writes if the underlying buffer is full. Therefore, you have to create a bunch of different threads if your server has a bunch of open Socket
s.
A SocketChannel
is a non-blocking way to read from sockets, so that you can have one thread communicate with a bunch of open connections at once. This works by adding a bunch of SocketChannel
s to a Selector
, then looping on the selector's select()
method, which can notify you if sockets have been accepted, received data, or closed. This allows you to communicate with multiple clients in one thread and not have the overhead of multiple threads and synchronization.
Buffer
s are another feature of NIO that allows you to access the underlying data from reads and writes to avoid the overhead of copying data into new arrays.