Open In App

ServerSocketChannel in Java NIO Package

Improve
Improve
Like Article
Like
Save
Share
Report

A Java NIO ServerSocketChannel is a channel that can listen for incoming TCP connections, just like a ServerSocket in standard Java Networking. The ServerSocketChannel class is located in the java.nio.channels package.

java.lang.Object
    java.nio.channels.spi.AbstractInterruptibleChannel
        java.nio.channels.SelectableChannel
            java.nio.channels.spi.AbstractSelectableChannel
                java.nio.channels.ServerSocketChannel

All Implemented Interfaces:

Closeable, AutoCloseable, Channel, InterruptibleChannel, NetworkChannel
public abstract class ServerSocketChannel
extends AbstractSelectableChannel
implements NetworkChannel

Constructor 

  • protected ServerSocketChannel(SelectorProvider provider): Initializes a new instance of this class.

Important methods of Socket channel

  • bind(SocketAddress local) − This method is used to bind the socket channel to the local address which is provided as the parameter to this method.
  • accept() − This method is used to accepts a connection made to this channel’s socket.
  • connect(SocketAddress remote) − This method is used to connect the socket to the remote address.
  • finishConnect() − This method is used to finishes the process of connecting a socket channel.
  • getRemoteAddress() − This method returns the address of the remote location to which the channel’s socket is connected.
  • isConnected() − As already mentioned this method returns the status of the connection of the socket channel i.e whether it is connected or not.
  • open() − Open method is used to open a socket channel for no specified address. This convenience method works as if by invoking the open() method, invoking the connect method upon the resulting server socket channel, passing it remotely, and then returning that channel.
  • read(ByteBuffer dst) − This method is used to read data from the given buffer through the socket channel.
  • setOption(SocketOption<T> name, T value) − This method sets the value of a socket option.
  • socket() − This method retrieves a server socket associated with this channel.
  • validOps() − This method returns an operation set identifying this channel’s supported operations. Server-socket channels only support the acceptance of new connections, so this method returns SelectionKey.OP_ACCEPT.

A selectable channel for stream-oriented listening sockets.

A server-socket channel is created by invoking the open method of this class. It is not possible to create a channel for an arbitrary, pre-existing ServerSocket. A newly-created server-socket channel is open but not yet bound. An attempt to invoke the accept method of an unbound server-socket channel will cause a NotYetBoundException to be thrown. A server-socket channel can be bound by invoking one of the bind methods defined by this class.

Socket options are configured using the setOption method. Server-socket channels support the following options:

Option Name         Description
SO_RCVBUF             The size of the socket receive buffer
SO_REUSEADDR        Re-use address

Additional (implementation-specific) options may also be supported.

Server-socket channels are safe for use by multiple concurrent threads.

Here is an example:

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

serverSocketChannel.socket().bind(new InetSocketAddress(9999));

while(true) {
   SocketChannel socketChannel = serverSocketChannel.accept();

   // Body
   // Do something with socketChannel...
}

A. Opening a ServerSocketChannel

You open a ServerSocketChannel by calling the ServerSocketChannel.open() method.

Syntax:

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

B. Closing a ServerSocketChannel

Closing a ServerSocketChannel is done by calling the ServerSocketChannel.close() method.

Syntax:

serverSocketChannel.close();

C. Listening for Incoming Connections

Listening for incoming connections is done by calling the ServerSocketChannel.accept() method. When the accept() method returns, it returns a SocketChannel with an incoming connection. Thus, the accept() method blocks until an incoming connection arrives.

Since you are typically not interested in listening just for a single connection, you call the accept() inside a while-loop. Here is how that looks:

Syntax:

while(true) {
   SocketChannel socketChannel = serverSocketChannel.accept();
   // Do something with socketChannel...
}

Of course, you would use some other stop-criteria than true inside the while-loop.

D. Non-blocking Mode

A ServerSocketChannel can be set into non-blocking mode. In non-blocking mode, the accept() method returns immediately, and may thus return null if no incoming connection had arrived. Therefore you will have to check if the returned SocketChannel is null. 

Illustration:

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

serverSocketChannel.socket().bind(new InetSocketAddress(9999));
serverSocketChannel.configureBlocking(false);

while(true) 
{
   SocketChannel socketChannel = serverSocketChannel.accept();

   if(socketChannel != null)
   {
       // Do something with socketChannel...
   }
}

Last Updated : 22 Sep, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads