Tuesday, October 30, 2012

Java Socket Programming




Sockets in some kind of device (basically a computer) provide the communication mechanism between two devices(computers) using TCP. A client program which represent the client end creates a socket (virtual) on its end of the communication and attempts to connect that socket to a server. 

When the connection is made, the server creates a socket object(virtual) on its end of the communication. Here server is another program . We can read and write to the socket. And the client program and the Server program can communicate through the socket. 

In java there is a package of the J2SE APIs called java.net which contains a collection of classes and interfaces that provides the capability to communicate using sockets. And we can write some handy programs using this package. 

 Java.net package supports TCP, which allows for reliable communication between two applications, (obviously) and UDP(User Datagram Protocol)

there are two important classes in this package which allow us to do those basic things.
·         java.net.Socket          -        represents a socket
·         java.net.ServerSocket         -       provides a mechanism for the server program to listen for clients and establish connections with them

let's start by understanding what is going on server side and client side when this communication through sockets happens.
  •          First the server initiates a ServerSocket object. It contains a port number to select which port is to use.
                ServerSocket   serverSocket = new ServerSocket(3000, 10);
                In here it use the constructor public ServerSocket(int port, int backlog) throws   IOException
                port = specifies port number
                backlog = specifies how many incoming clients to store in a wait queue 
  •          Now the server has to  listen. Until  someone connect to the port. To do that the Server  Socket class has a method called accept().
                Socket connection = serverSocket.accept();
  •          Now a client is trying to connect. To do that client initiates a Socket object which specify a server name and a port.
                Socket clientSocket = new Socket("localhost", 3000);
                here the server and the client both are running on a same machine using local host(otherwise this "localhost" should be any other valid IP address ). Client should try to connect to the same port (3000 , this can be any valid port number)
  •         Now the constructor of the Socket class try to connect the client to the specified server and the port.
  •        If the connection successful then , accept()  method of the server will returns a reference of the new Socket.
  •         Now the server and the client can communicate using that Socket.

========================================================================


Server code
 

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

public class Server  {

    ServerSocket serverSocket;
    Socket connection = null;
    ObjectOutputStream out;
    ObjectInputStream in;
    String message;
    //this is for maitainig a state(not necessary)
    static boolean state = true;

    Server () {
    }

    void run() {
        try {
            // creating a Server socket
            serverSocket = new ServerSocket(3000, 10);

            // Waiting for a client to  connect to the port
            System.out.println("Waiting for connection....");
            connection = serverSocket.accept();
            System.out.println("Connection successfully received from " + connection.getInetAddress().getHostName());
            // get Input and Output streams
            out = new ObjectOutputStream(connection.getOutputStream());
            out.flush();
            in = new ObjectInputStream(connection.getInputStream());

            // Communication part with the server
            // ah. now do what ever you want :D

            try {

                String msg = "Enter your name : ";
                sendMessage(msg);
                message = (String) in.readObject();
                System.out.println("client>" + message);
                if (message.equals("vidudaya")) {
                    sendMessage("Rocognized user.. welcome " + message + ".....");
                } else {
                    sendMessage("New user.. welcome " + message + ".....");
                }


                sendMessage("continue...(y/n)");
                message = (String) in.readObject();
                if (!message.equals("y")) {
                    state = false;
                    sendMessage("bye");
                } else {
                    sendMessage("c u some other time...");
                    state = false;
                }

            } catch (ClassNotFoundException classnot) {
                System.err.println("Data received in unknown format");
            }



        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            //Closing connection
            try {
                in.close();
                out.close();
                serverSocket.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    void sendMessage(String msg) {
        try {
            out.writeObject(msg);
            out.flush();
            System.out.println("server>" + msg);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    public static void main(String args[]) {
        Server  server = new Server();
        while (state) {
            server.run();
        }
    }
}
Client code
 

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Client {

    Socket clientSocket;
    ObjectOutputStream out;
    ObjectInputStream in;
    String message;
    // to  read inputs
    Scanner sc = new Scanner(System.in); 

    Client () {
    }

    void run() {
        try {
            //  creating a Socket to connect to the server
            clientSocket = new Socket("localhost", 3000);
            System.out.println("Connected to localhost in port 3000");
            
            // get Input and Output streams
            out = new ObjectOutputStream(clientSocket.getOutputStream());
            out.flush();
            in = new ObjectInputStream(clientSocket.getInputStream());
           
            // Communication part with the server
             // here you can play as you want :D
            
            try {
                message = (String) in.readObject();
                System.out.println("server>" + message);
                String reply = sc.next();
                sendMessage(reply);
                message = (String) in.readObject();
                System.out.println("server>" + message);
                message = (String) in.readObject();
                System.out.println("server>" + message);

                sendMessage(sc.next());
                message = (String) in.readObject();
                System.out.println("server>" + message);
                
                if (message.equals("bye")) {
                    System.exit(0);
                }

            } catch (ClassNotFoundException classNot) {
                System.err.println("data received in unknown format");
            }

        } catch (UnknownHostException unknownHost) {
            System.err.println("You are trying to connect to an unknown host!");
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            //Closing the connection
            try {
                in.close();
                out.close();
                clientSocket.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }    

    // this method is used to send the message through the Socket
    void sendMessage(String msg) {
        try {
            out.writeObject(msg);
            out.flush();
            System.out.println("client>" + msg);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    public static void main(String args[]) {
        Client client = new Client();
        client.run();
    }
}
================================================================================= The two programs can be in the same package. But it is not really necessary.(We are accessing the Socket, so does not matter where the server or client is deployed :D )
 But here. First run the Server code. And then run the Client code. (Client must have a working server first :D)

0 comments:

Post a Comment