Tuesday, 8 December 2015

Server Client socket programming in Java

This tutorial is made with a purpose of understanding the basic concepts of socket programming with Java. For socket programming you need a package java.net which is within J2SE API's, which consists of classes and interface for low level communications. java.net supports communication with 2 types of protocols,
TCP (Transmission Control Protocol) and UDP (User Datagram Protocol). In this tutorial we are dealing with to application, one Server and another Client. When the Server program starts it listens for client request on the host address given and on a given port number. Ports already in use cannot be used, server is also set to a timeout after 10 seconds. Then the client program which whenever connects to the server, server accepts connection and sends a reply to the client.

1. SocketServer.java.

/*Import these 2 packages, first one is for socket programming and the second one is for input output streaming. */
import java.net.*;
import java.io.*;

public class SocketServer extends Thread
{
   private ServerSocket serverSocket;

   public SocketServer(int port) throws IOException
   {
     
      serverSocket = new ServerSocket(port);
      serverSocket.setSoTimeout(10000);    
    }

    public void run()
    {
        while(true)
        {
            try
            {
                System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "....");
                Socket server = serverSocket.accept();
                System.out.println("Connected to " + server.getRemoteSocketAddress());
                DataInputStream in  = new DataInputStream(server.getInputStream());
                System.out.println(in.readUTF());
                DataOutputStream out = new DataOutputStream(server.getOutputStream());
                out.writeUTF("Thanks for connecting to " + server.getLocalSocketAddress());
                server.close();          
            }
            catch(SocketTimeoutException s)
            {
                System.out.println("\nSocket time out..");
                break;
            }
            catch(IOException e)
            {
                System.out.println(e.getMessage());
                break;
            }
        }
    }

    public static void main(String[] args)
    {
        int port = Integer.parseInt(args[0]);
        try
        {
            Thread t = new SocketServer(port);
            t.start();          
        }
        catch(IOException e)
        {
            System.out.println(e.getMessage());
        }
    }
}

2. SocketClient.java

import java.net.*;
import java.io.*;

public class SocketClient
{
    public static void main(String[] args)
    {
        String serverName = args[0];
        int port = Integer.parseInt(args[1]);
        try
        {
            System.out.println("Connecting to " + serverName + " on port " + port);
            Socket client = new Socket(serverName, port);
            //client.connect();
            System.out.println("Connected to " + client.getRemoteSocketAddress());
            OutputStream outServer = client.getOutputStream();
            DataOutputStream out = new DataOutputStream(outServer);
            out.writeUTF("\nHello from " + client.getLocalSocketAddress());
            InputStream inServer = client.getInputStream();
            DataInputStream in = new DataInputStream(inServer);
            System.out.println("Server says..." + in.readUTF());
            client.close();           
        }
        catch(IOException e)
        {
            System.out.println(e.getMessage());
        }
    }
}

No comments: