Java NIO SocketChannel
The Java NIO SocketChannel is used for connecting a channel with a TCP (Transmission Control Protocol) network socket. It is equivalent to Java Networking Sockets used in network programming.
There are two methods available for creating a SocketChannel in Java NIO:
- It can be created when an incoming connection arrives at the ServerSocketChannel.
- We can open a SocketChannel and connect with a server anywhere using an internet.
Let’s see the block diagram of SocketChannel Client-Server Communication using a Selector:
Closing a SocketChannel
We can close a SocketChannel after performing all operations by calling the SocketChannel.close() method.
The syntax used for closing a socket channel is:
Opening a SocketChannel
We can open a SocketChannel by calling the SocketChannel.Open() method.
The syntax used for opening a socket channel is:
Reading from a SocketChannel
For reading the data from a SocketChannel we call one of the read() methods.
Let’s see the example of reading the data from a SocketChannel:
Firstly the buffer is allocated. The data read from a SocketChannel is stored into the buffer.
Secondly we call the SocketChannel.read() method and it reads the data from a SocketChannel into a buffer. The integer value of the read() method returns how many bytes were written into the buffer.
Writing to a SocketChannel
For writing the data to a SocketChannel the SocketChannel.write() method is use and it takes the buffer as a parameter.
Let’s see the example of writing the data to a SocketChannel:
The SocketChannel.write() method is used inside a while-loop because the number of bytes the write() method writes to a SocketChannel is not known, therefore we repeat the write() method until the Buffer has no further bytes available to write.