Socket vs SocketChannel

Ramzi Khahil picture Ramzi Khahil · Jan 9, 2013 · Viewed 40.5k times · Source

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:

  • What is a SocketChannel?
  • What is the extra I get when working with a SocketChannel instead of a Socket.
  • What is the relationship between a channel and a buffer?
  • What is a selector?
  • The first sentance in the documentation is 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...

Answer

Andrew Mao picture Andrew Mao · Jan 9, 2013

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 Sockets.

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 SocketChannels 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.

Buffers 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.