Java NIO ServerSocketChannelThe Java NIO ServerSocketChannel is also used for connecting a channel with a TCP (Transmission Control Protocol) network socket. It is equivalent to Java Networking Sockets used in network programming. The class of ServerSocketChannel is located in the java.nio.channels package. Let's see the example of ServerSocketChannel: Closing a ServerSocketChannelWe can close a ServerSocketChannel after performing all operations by calling the ServerSocketChannel.close() method. The syntax used for closing a ServerSocketChannel is: Opening a ServerSocketChannelWe can open a ServerSocketChannel by calling the ServerSocketChannel.open() method. The syntax used for opening a ServerSocketChannel is: Listening for Incoming ConnectionsIt is done by calling the ServerSocketChannel.accept() method. The accept() method is used for returning a SocketChannel with an incoming connection. Let's see the example for listening an incoming connection is: We call the accept() method inside a while-loop because we want to listen for all incoming connections. Reading from a ServerSocketChannelFor reading the data from a ServerSocketChannel we call one of the read() methods. Let's see the example of reading the data from a ServerSocketChannel: Firstly the buffer is allocated. The data read from a ServerSocketChannel is stored into the buffer. Secondly we call the ServerSocketChannel.read() method and it reads the data from a ServerSocketChannel into a buffer. The integer value of the read() method returns how many bytes were written into the buffer. Writing to a ServerSocketChannelFor writing the data to a ServerSocketChannel the ServerSocketChannel.write() method is use and it takes the buffer as a parameter. Let's see the example of writing the data to a ServerSocketChannel: The ServerSocketChannel.write() method is used inside a while-loop because the number of bytes the write() method writes to a ServerSocketChannel is not known, therefore we repeat the write() method until the Buffer has no further bytes available to write. Next TopicJava NIO Pipe |
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