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.

No comments:

Post a Comment