Friday, September 7, 2012

How to create Client Side and Server Side Sockets in Java?


Client-Side Socket :

Socket created at the client side of the communication link is known as Client-side Socket. It is used to connect to the server.

Example Code :
In following program, client socket is created to communicate with server. We have to pass three command-line arguments :
    The host name of the server
    The Port of the server, where service is available
    A Message to send to the server

//Client.java

package net.client;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
 public static void main(String[] args) {
   if(args.length !=3){
  System.out.println("Usage: java clientside Hostname port message");
  System.exit(0);
  }
  String serverName = args[0];
  int serverPort = Integer.parseInt(args[1]);
  String message = args[2];
      try {
        Socket socket = new Socket(serverName,serverPort); //Client Socket
        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
  dos.writeUTF(message);
  dos.close();
  } catch (UnknownHostException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}


Server-Side Socket : Server-side Socket is created at the server end of communication link. It is used to provide services at the server end. ServerSocket is a class, that is used to create Server socket.
Example Code :
This example creates a server socket using the ServerSocket class. It waits for a client to connect to the server and then displays a message sent by the client.


//Server.java

package net.server;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
 public static void main(String[] args) {
  try {
   ServerSocket serverSocket = new ServerSocket(1234);
     System.out.println("Server listening at "+ InetAddress.getLocalHost() +" on port "+serverSocket.getLocalPort());
   while(true){    
    Socket socket = serverSocket.accept();
    DataInputStream dis = new DataInputStream(socket.getInputStream());
    String message = dis.readUTF();
    String str = message+" To Java";
    System.out.println(str);   
   }
   
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}


Now we have to compile and run both the java programs.
First, let us compile Server.java and run the program. Server should be ready for receiving the messages from the Client.

 Now we have to compile Client.java and run the program with passing three command-line arguments.

Difference between Socket and Port

Although socket is not a port but it has close relationship with port. A socket is associated with a port, though a many-to-one relationship. Each port can have a single passive socket, awaiting incoming connections, and multiple active sockets, each corresponding to an open connection on the port.

Socket 
It is an endpoint of a bidirectional communication over a network.
It is associated with port. It is communication path to a port.


In a very simple term, we can represent a socket as :
Socket = IP Address + Port Number
It is just like a telephone connection (IP Address) with the extension(Port No).

Sockets are of two types :
Active Socket
It is connected to a remote active socket through a open data connection.

Passive Socket
It does not participate in an open connection, but wait for an incoming connection.

Port
It is a logical data connection that can be used to exchange data between client and server. 
It is represented through a port number starts from 0  and goes up to 65535.  
There are three different categories of Port Numbers:
0 - 1023 System Ports
1024 -  49151 User Ports
49152 - 65535 Dynamic Ports

System Ports are assigned by IETF (Internet Engineering Task Force) .
User Ports are assigned by IANA (Internet Assigned Numbers Authority ).
Dynamic Ports are not assigned.

If you are interested to know how we can create Client-Side and Server-Side Sockets in java, here is a link ..
Creating Client-Side and Server-Side Sockets in Java