Java NIO SocketChannelThe 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:
Let's see the block diagram of SocketChannel Client-Server Communication using a Selector: Closing a SocketChannelWe 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 SocketChannelWe can open a SocketChannel by calling the SocketChannel.Open() method. The syntax used for opening a socket channel is: Reading from a SocketChannelFor 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 SocketChannelFor 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. Next TopicJava NIO ServerSocketChannel |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India