All About Class ServerSocket in Java

0
41
Spread the love
  • 24
  • 34
  • 28
  • 35
  •  
  •  
  •  
  • 12
  •  
  •  
    133
    Shares

ServerSocket in Java
ServerSocket in Java
ServerSocket in Java

All About Class ServerSocket in Java

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

An application can change the socket factory that creates the socket implementation to configure itself to create dockets appropriate to 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 any exception, it means that application has successfully bound to the specified port and is ready for 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 client,upon receiving the request , it creates and returns a Socket that the server can use to the communicate.

An application acting as server creates a ServerSocket object and waits,blocked in a call to it’s accept() 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 conversation at once.There is only a single ServerSocket but one active socket object for each of the client.

Clientsocket and Server Socket
Clientsocket and Server Socket

A client need two piece of information to locate and connect to server on internet.

  1. Host Name
  2. Port Number

Host name can be an ip. Post number is an identifier that differentiates between multiple clients on the server (on the same host name.). 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
}
 

public ServerSocket(int port) throws IOException;

This 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.OException can also occur if the port is already bound by another application.

public ServerSocket(int port,int count)throws IOException

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.

public ServerSocket(int port,int count,InetAddress address)throws IOException

creates a server socket and binds it to the specified local post number.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.

public ServerSocket()throws IOException

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

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.

How Server Works?

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 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.)

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 24
  • 34
  • 28
  • 35
  •  
  •  
  •  
  • 12
  •  
  •  
    133
    Shares

LEAVE A REPLY

Please enter your comment!
Please enter your name here