Class ServerSocket in Java

digitization, transformation, binary

All About Class ServerSocket in Java

ServerSocket class implements server sockets. A server socket waits for requests to come in over network from clients on a specific port. It performs some operation based on that request and then possibly return a result to the requester. The actual work of the server socket is performed by an instance of the SocketImpl class.

The low-level network access in ServerSocket is provided by a subclass of the abstract class SocketImpl. An application can change the server socket factory that creates the SocketImpl subclass by supplying a SocketImplFactory using the setSocketFactory() method. This feature allows an application to create sockets that are appropriate for the local network configuration and accommodate such things as firewalls.

Ads code goes here

An application can change the socket factory that creates the socket implementation to configure itself to create sockets appropriate to the local firewall. ServerSocket class is used by server applications to obtain a port and listen for client requests.

If the ServerSocket constructor does not throw an exception, it means that the application has successfully bound to the specified port and is ready for a client request.
When we create a ServerSocket, we specify the port to listen on. The accept() method starts listening on that port. The ServerSocket also blocks the port until the server is done with the client communication.accept() accepts a connection request from a client, upon receiving the request, it creates and returns a Socket that the server can use to the communicate.

An application acting as a server creates a ServerSocket object and waits, blocked in a call to it’s accepted () method until a connection arrives.

When a connection arrives, the accept() method creates a Socket object the server uses it to communicate with the client. A server carries on multiple conversations at once. There is only a single ServerSocket but one active socket object for each of the clients.

A client needs two pieces of information to locate and connect to the server on the internet.

  1. Host Name
  2. Port Number

The hostname can be an IP. Post number is an identifier that differentiates between multiple clients on the server (on the same hostname.). As discussed earlier, a server application listens on a prearranged port while waiting for connections. Clients, on the other hand, select the port number assigned to service, they want to access.

The structure of the class ServerSocket is given as:

public final class java.net.ServerSocket extends java.lang.Object{
//contructors
public ServerSocket(int port) throws IOException;
public ServerSocket(int port,int count)throws IOException;
public ServerSocket(int port,int count,InetAddress address)throws IOException;
//methods
public Socket accept()throws IOException;//waits for incoming client. This method blocks until either a client connects to the server on the specified port or the socket times out. Assuming that the time-out value has been set using the setSoTimeout() method.Otherwise, it will blocks indefinitely.
public void close() throws IOException;
public InetAddress getInetAddress();
public int getLocalPort();//returns the port that the server socket is listening on.This method is very useful when we pass 0 as the port number in the constructor and let the server finds the suitable port for us.
public synchronized void setSoTimeOut(int timeout) throws SocketException;//sets the
// time out value for how long the server
// socket waits for a client during accept();
public static synchronized void setSocketFactory(SocketImplFactory factry) throws IOException;
public void bind(SocketAddress host,int backlog);
//Binds the socket to the specified server and port in the SocketAddress object. 
//This is applicable if no argument constructor has been initiated for server socket.
public synchronized int getSoTimeOut() throws IOException;
public String toString();//overrides the Object
protected final void implAccept(Socket sock) throws IoException
}
 

The details of the class structure are given as follows:

public ServerSocket()

public ServerSocket() constructor creates an unbound server socket. When using this constructor, we need to use the bind() method when we are ready to bind the server socket.

READ  Class ZipFile in Java

When the ServerSocket invokes accept(), the method does not return until a client connects. After a client does connect, the ServerSocket creates a new Socket on an unspecified port and returns a reference to this new Socket. A TCP connection now exists between the client and the server. Post this communication can happen.

public ServerSocket(int port);

public ServerSocket(int port) contractor creates a server socket on the specified port. A port (of 0) object creates a socket on any free port. The maximum queue length for incoming connection indication arrives when the queue is full, the connection request is refused. If the application has specified a server socket factory, the factory’s createSocketImpl() method is called to create the actual socket implementation. Otherwise, a plain socket is created. It may throw IOException if an I/O error occurs while opening the socket.IOException can also occur if the port is already bound by another application.

Parameter
port – A port number, or 0 for any available port.

public ServerSocket(int port, int backlog);

public ServerSocket(int port, int backlog) constructor creates a server socket and binds it to the specified local port number. A port number of 0 creates a socket on any free port available.count is often referred by backlog. The maximum queue length for incoming connection request indication( request to connect) is set to count parameter. If a connection indication arrives when the queue is full, the connection is refused. If the application has specified a server socket factory, the factory’s createSocketImpl() method is called to create the actual socket implementation. Otherwise, a plain socket is created. It may throw IOException if an I/O error occurs while opening the socket.

Parameter
port – A port number, or 0 for any available port.
backlog – The maximum length of the pending connections queue.

public ServerSocket(int port, int backlog,InetAddress bindAddr);

public ServerSocket(int port, int backlog,InetAddress bindAddr) constructor creates a server socket and binds it to the specified local port number. The InetAddress parameter specifies the local IP address to bind to. The InetAddress is used for servers that may have multiple IP addresses, allowing the server to specify which of it’s IP address to accept client requests on. A port number of 0 creates a socket on any free port available.count is often referred by backlog. The maximum queue length for incoming connection request indication( request to connect) is set to count parameter. If a connection indication arrives when the queue is full, the connection is refused. If the application has specified a server socket factory, the factory’s createSocketImpl() method is called to create the actual socket implementation. Otherwise, a plain socket is created. It may throw IOException if an I/O error occurs while opening the socket.

READ  Hire Java Builders With Working experience in Top 10 Java Frameworks

Parameter
port – A port number, or 0 for any available port.
backlog – The maximum length of the pending connections queue.
bindAddr – A local address.

public static synchronized void setSocketFactory(SocketImplFactory fac);

public static synchronized void setSocketFactory(SocketImplFactory fac) method is used to set the SocketImplFactory. This factory object produces instances of subclasses of SocketImpl that do the low-level work of server sockets. When a ServerSocket constructor is called, the createSocketImpl() method of the factory is called to create the server socket implementation.

Parameter
fac – An object that implements SocketImplFactory.

public Socket accept();

public Socket accept() method accepts a connection and returns a Socket object to handle communication. If there are pending connections, the method accepts a pending connection from the queue and returns immediately. Otherwise, the method may block until a connection is requested. If a time-out value has been specified using the setSoTimeout()
method, accept() may time out and throw an InterruptedIOException if no connection is requested in the time-out period.

This method returns a Socket object for the connection.

public void close();

public void close() method closes this server socket, releasing any system resources it holds.

public InetAddress getInetAddress();

public InetAddress getInetAddress() method returns the address of the local host in general. However, a ServerSocket can be constructed with an alternate address using ServerSocket(int, int, InetAddress). The method returns null if the socket is not yet connected.

This method returns the IP address to which this ServerSocket is listening.

public int getLocalPort();

public int getLocalPort() method returns the port number to which this object is connected.

This method returns the port number to which this ServerSocket is listening.

public synchronized int getSoTimeout() 

public synchronized int getSoTimeout() method returns the receive time-out value for this socket. A value of zero indicates that accept() waits indefinitely for an incoming packet, while a non-zero value indicates the number of milliseconds it waits.

This method returns the receive timeout value for the socket.

public synchronized void setSoTimeout(int timeout);

public synchronized void setSoTimeout(int timeout) method is used to set the time-out value that is used for accept(). A nonzero value is the length of time, in milliseconds, the ServerSocket should wait for a connection. A value of zero indicates that the ServerSocket should wait indefinitely. If a time-out value is needed, this method must be called before accept().

READ  ENUM Concept Simplified In Java

Parameter
timeout – The new time-out value, in milliseconds, for this socket.

public String toString();

public String toString() method returns a String that contains the address and port of this ServerSocket.

This method returns the string representation of this ServerSocket.

protected final void implAccept(Socket s);

protected final void implAccept(Socket s) method is a helper method for accept(). It can be overridden in subclasses of ServerSocket to support new subclasses of Socket.

Parameter
s– The Socket object to be connected.

Apart from these methods, ServerSocket class also has inherited methods from class- Object. They are as follows:

  • clone()
  • finalize()
  • hashCode()
  • notifyAll()
  • wait()
  • wait(long, int)
  • equals(Object)
  • getClass()
  • notify()
  • toString()
  • wait(long)

How Does Server work?

Once the connection has been established a server uses some kind of socket object for its side of the connections. However, to accept a connection from the client, it must first create ServerSocket bound to the correct port.

try{
ServerSocket listener=new ServerSocket(9996);
while(!finished)
{
//wait for a connection
Socket server=listener.accept();
InputStream in=server.getInputStream();
OutputStream out=server.getOutputStream();
//Read a byte
Byte getByte=in.read();
//Read a String
DataInputStream dim=new DataInputStream(out);
String request=dim.readLine();
//Write a byte
out.write(44);
//Write a String
PrintStream pOut=new PrintStream(out);
pOut.println("Hi from Server");
server.close();
}
listener.close();
}
catch(IOException){}

At first, the server creates a ServerSocket on port -9996.(There could be application-specific rules on what port can b used and what can not be used.)

The ServerSocket needs to be created only once. Then we can accept as many client connections as they arrive.

Next, the code enters into a loop, waiting for the accept() method of the ServerSocket to return an active socket connection from the client. When a connection has been established, we can perform the server-side of the message exchange.

Once those activities are done, it closes the connection and returns to the loop to wait for another client connection.

Finally, when the server wants to close the connection and stops listening, it calls the close() method of the ServerSocket.

Note:

A security feature of TCP/IP specifies that if a ServerSocket actively closes a connection while the client is connected, it may not be able to bind(attach itself) to the same port on the server host again for a certain period. It is possible to turn this feature off in java.

This kind of sever(shown above) is single-threaded and it handles one connection at a time. It does not call accept() method to listen for a new connection until it finishes the current connection. However, practically a server can accept ‘n’ number of requests and concurrently serve them by passing them off to their threads for processing.

Share and Enjoy !

Leave a Comment

Your email address will not be published. Required fields are marked *