Thursday, December 26, 2013

Client-Server Socket Programming in Java


Hey geeks, today I would like to share about some networking concepts like socket programming in Java. We will see how to communicate between Server and Clients using core Java programming. Socket programming can be done in many langauges, basically it's done in C programming because C is a system programming langauge but in Java it's quite easier then the C programming. We can say, the magic in socket programming is that it's not necessary that your Server and Client both should be written in same langauges, it can be possible to write Server code in C programming and Client in Java programming and vice-versa. But there should be proper sycncronization and it's depends on the logic of programmer who is concern with the Application he/she is doing. Here I am considering that you guys have the basic knowledge of Socket programming and the methods used in it.

 

Implementing a Server :-

1. Open the Server Socket:
ServerSocket server;
DataOutputStream os;
DataInputStream is;
server = new ServerSocket( PORT );
2. Wait for the Client Request:
Socket client = server.accept();
3. Create I/O streams for communicating to the client
is = new DataInputStream( client.getInputStream() );
os = new DataOutputStream( client.getOutputStream() );
4. Perform communication with client
Receive from client: String line = is.readLine();
Send to client: os.writeBytes("Hello\n");
5. Close sockets: client.close();

Implementing a Client :-

1. Create a Socket Object:
client = new Socket( server IP address, port_id );
2. Create I/O streams for communicating with the server.
is = new DataInputStream(client.getInputStream() );
os = new DataOutputStream( client.getOutputStream() );
3. Perform I/O or communication with the server:
Receive data from the server:
String line = is.readLine();
Send data to the server:
os.writeBytes("Hello\n");
4. Close the socket when done:
client.close();


While implementing Client, when we create client socket we must have to give the server IP address and port number. Here port number should be same as server port number. All port number less then equal to 1024 are reservered so for our use we can used any of them as per thier application or else we can assign our own port number that should be greater then 1024. Following figure illustrated a sample demo of it.
Fig - 01
Fig - 02

I am also giving the source code for the Server-Client programmig in Java to calculate Sum of Number,Fact and String operation on a string. If you want to run this program on your system make the IP address as “localhost” or “127.0.0.1”(IP of localhost) and if you want to run this program in network then make the IP address, IP address of your Server. 
Client :-
import java.io.*;
import java.io.DataInputStream;
import java.net.*;
class Client
{
    public static void main(String arg[])throws Exception
    {
       
        Socket client=new Socket("172.16.3.192",2015);
        DataInputStream r=new DataInputStream(client.getInputStream());
        PrintStream w=new PrintStream(client.getOutputStream());
        DataInputStream in=new DataInputStream(System.in);
            while(true)
            {
                System.out.println("\t\t\n[ MENU ]\n[1].Fact\n[2].Sum of Number\n[3].String operation\n[4].Exit\n\nEnter your Choice :");
                int choice=Integer.parseInt(in.readLine());
                switch(choice)
                {
                    case 1: System.out.println("\nEnter a Number:");
                        int num=Integer.parseInt(in.readLine());
                        w.println(choice);w.println(num);   
                        String fact=r.readLine();
                        System.out.print("\nFact of Number is :"+fact);
                        break;
                    case 2: System.out.println("\nEnter a Number:");
                        int num1=Integer.parseInt(in.readLine());
                        w.println(choice);w.println(num1);   
                        String sum=r.readLine();
                        System.out.print("\nSum of Number is :"+sum);
                        break;
                    case 3:    System.out.println("\nEnter a string:");
                        String str=in.readLine();
                        w.println(choice);w.println(str);   
                        String len=r.readLine();
                        System.out.print("\nLenght of String is  :"+len);
                        String rev=r.readLine();
                        System.out.print("\nReverse of  String : "+rev);
                        if(str.equals(rev))
                        {
                            System.out.println("\nA given String is Palindrome");
                        }
                        else
                        {
                        System.out.println("\nA given String is not Palindrome");
                        }
                        break;
                    case 4: choice=0;
                        w.println(choice);client.close();System.exit(0);
                        break;
                    default :  System.out.println("\nWrong Choice....");
                            break;
                   
                }
               
            }
    }
Server :-
import java.io.*;
import java.io.DataInputStream;
import java.net.*;
class Server
{
    public static void main(String[] arg)throws Exception
    {
       
        ServerSocket server=new ServerSocket(2015);
        System.out.printf("\nServer Started SuccessFully");
        Socket client=server.accept();
        DataInputStream r=new DataInputStream(client.getInputStream());
        PrintStream w=new PrintStream(client.getOutputStream());
        DataInputStream in=new DataInputStream(System.in);
        while(true)
        {
           
            int choice=Integer.parseInt(r.readLine());
            String data=r.readLine();
            switch(choice)
            {
                case 1:
                    int num=Integer.parseInt(data);
                    int fact=1;
                    while(num>0)
                    {
                        fact=fact*num--;
                    }
                    w.println(fact);
                    System.out.printf("\nFact is calculated and send back to Client...\n");
                    break;   
                case 2:
                    int num1=Integer.parseInt(data);
                    int sum=0;
                    while(num1!=0)
                    {
                        sum=sum+(num1 % 10);num1=num1/10;
                    }
                    w.println(sum);
                    System.out.printf("\nSumof number is calculated and send back to Client...\n");
                    break;
                case 3:
                    w.println(data.length());
                    StringBuffer buffer = new StringBuffer(data);
                    w.println(buffer.reverse());
                    System.out.printf("\nString Operations are done and send back to Client...\n");
                    break;
                case 0:server.close();System.exit(0);break;   
            }
        }

    }