TCP ServerSocket Program

Below is Server program, based on TCP/IP. For details on TCP, please read Java Networking
Step 1.import java.net and java.io packages
Step 2.Create ServerSocket Listening on a port
Step 3.Waits for 65000 milliseconds for request from any client. On receiving a request from client, read request from client
Step 4.Print client request on server console
Step 5.Now send response to client program.

SocketServer Example
SocketServer example

Using Thread for a server is not mandatory, and can be used for better performance, if required

//step 1
import java.net.*;
import java.io.*;

public class HelloServer extends Thread
{
   private ServerSocket server_obj;

   public HelloServer(int port) throws IOException
   {
     //step 2, Create ServerSocket and listen on a port
      server_obj = new ServerSocket(port, 5);//5 is number of back log requests

      //waits for 65000 milliseconds to receive request from client
      //If no request is received from client within 65000, SocketTimeoutException is thrown
      server_obj.setSoTimeout(65000);
   }

   public void run()
   {
    for(;;) //infinite for loop
    {
    try
    {
       System.out.println("Server: ..Waiting for client request on port number " +
       server_obj.getLocalPort() );
       //step 3
       Socket server = server_obj.accept();
       System.out.println("Server: Connecting to client with IP addr "
             + server.getRemoteSocketAddress());
       DataInputStream in =
             new DataInputStream(server.getInputStream());
       //step 4
       System.out.println(in.readUTF());

       //step 5
       DataOutputStream out =
            new DataOutputStream(server.getOutputStream());
       out.writeUTF("[From Server] This message is from server "
         + server.getLocalSocketAddress() + " Thanks for your request");
       server.close();
    }
    catch(SocketTimeoutException s)
    {
       System.out.println("Server: SocketTimeoutException occurred");
       s.printStackTrace();
       break;
    }
    catch(Exception ep)
    {
       System.out.println("Server: Exception occurred");
       ep.printStackTrace();
       break;
    }
    }
   }
   public static void main(String [] args)
   {
       //port number on which server is listening
       //clients need to send request to this port number
      int port_number = 6066;
      try
      {
         Thread t = new HelloServer(port_number);
         t.start();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

You may also like to read:
Step by Step Socket Client Program
What is Remote Method Invocation?
Where does printStackTrace() print to?
Can I create Child Thread to another Child Thread?

One thought on “TCP ServerSocket Program”

Leave a Reply