ServerSocketChannel in Java NIO Package
Last Updated :
22 Sep, 2021
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...
}
}
Similar Reads
Java ServerSocket Class
ServerSocket Class in Java provides a system-independent way to implement the server side of a client/server socket connection. The constructor for ServerSocket throws an exception if it canât listen on the specified port (for example, the port is already being used).In the java.nio channel, ServerS
4 min read
Multithreaded Servers in Java
Prerequisites: Socket Programming in Java Multithreaded Server: A server having more than one thread is known as Multithreaded Server. When a client sends the request, a thread is generated through which a user can communicate with the server. We need to generate multiple threads to accept multiple
5 min read
Socket Programming in Java
Socket programming in Java allows different programs to communicate with each other over a network, whether they are running on the same machine or different ones. This article describes a very basic one-way Client and Server setup, where a Client connects, sends messages to the server and the serve
6 min read
Transfer the File "Client Socket to Server Socket" in Java
Prerequisites: Socket Programming in JavaFile Handling in JavaThis article describes a one-way client and Server Setup where a client connects, and sends the file to the server and the server writes the file in another location with a different name. It means we send the file using the server socket
4 min read
Non Blocking Server in Java NIO
Java NIO(New Input/Output) is high-performance networking and file handling API and structure which works as an alternative IO API for Java. It is introduced from JDK 4 which works as the second I/O system after standard Java IO with some added advanced features. It provides enhanced support for fil
8 min read
SimpleFileServer in Java
A server is a computer that is dedicated solely to the purpose of serving. It serves files to its clients whenever requests are made, and it should always be available. A program running on a port within the server is used to handle requests. The term 'server' can refer to a physical or virtual comp
7 min read
java.net.Socket Class in Java
The java.net.Socket class allows us to create socket objects that help us in implementing all fundamental socket operations. We can perform various networking operations such as sending, reading data and closing connections. Each Socket object that has been created using with java.net.Socket class h
5 min read
Legacy Socket API in Java
The Java Socket API has been around for more than two decades. It has been maintained and updated over that period, but even the most well-kept code ultimately has to be upgraded to stay up with contemporary technologies. The fundamental classes that handle Socket interaction in Java 13 have been re
4 min read
Java.net.MulticastSocket class in Java
This class is used for sending and receiving multicast IP packets. It extends DatagramSocket class and provides additional functionality for joining groups. A message sent to the group IP address will be received by all the clients who have joined the group. This must be kept in mind that for sendin
6 min read
Java.io Package in Java
Java.io Package in JavaThis package provides for system input and output through data streams, serialization and the file system. Unless otherwise noted, passing a null argument to a constructor or method in any class or interface in this package will cause a NullPointerException to be thrown. Follo
1 min read