Pages

Tuesday, February 16, 2010

TCP and UDP Client Server Programs In JAVA


A Simple Server and Client Examples

A simple client and the server programs are explained for all the types of techniques. A code samples for the connection-oriented, next for the connectionless and then for broadcasting are as follows.

Connection-oriented Client and Server : ( TCP )

The client sends the message " Hi from client " and the server response will be " Hello from Server ".

Server Program

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

public class Server{

//port number should be more than 1024

public static final int PORT = 1025;
         
public static void main( String args[])
{
 ServerSocket sersock = null;
 Socket sock = null;
 System.out.println(" Wait !! ");

 try
 {
  //  Initialising the ServerSocket
  sersock =  new ServerSocket(PORT);
                
  // Gives the Server Details Machine name, 
  Port number

  System.out.println("Server Started  :"+sersock);

  try
  {
                        
   // makes a socket connection to particular 
   client after 
   // which two way communication take place

   sock = sersock.accept();

   System.out.println("Client Connected  :"+ sock);

   // Receive message from client i.e Request 
   from client

   DataInputStream ins = new                 
   DataInputStream(sock.getInputStream());
   // Send message to the client i.e Response

   PrintStream ios = new   
   sPrintStream(sock.getOutputStream());
   ios.println("Hello from server");
   ios.close();

   // Close the Socket connection 
        
    sock.close();

    }
 catch(SocketException se)
 {
    System.out.println("Server Socket
  problem  "+se.getMessage());
    }
 catch(Exception e)
 {
    System.out.println("Couldn't start " 
                  + e.getMessage()) ;     
    }               
                        
 // Usage of some methods in Socket class

  System.out.println(" Connection from :  " + 
  sock.getInetAddress());
                
 } // main 
        
}  // Server class
 

Client Program

import java.lang.*;
import java.io.*;
import java.net.*;
import java.net.InetAddress;


class client
{
 Public static void main(String args[])
 {
 Socket sock=null;
 DataInputStream dis=null;
 PrintStream ps=null;
 System.out.println(" Trying to connect");
                                   
 try 
 {
 // to get the ip address of the 
 server by the name
              
 InetAddress ip =InetAddress.getByName
 ("Hari.calsoftlabs.com");

 // Connecting to the port 1025 declared 
 in the Serverclass
 // Creates a socket with the server
  bind to it.

  sock= new Socket(ip,Server.PORT);
  ps= new PrintStream(sock.getOutputStream());
  ps.println(" Hi from client");
  DataInputStream is = new 
  DataInputStream(sock.getInputStream());
  System.out.println(is.readLine());

 }
 0catch(SocketException e)
 {
  System.out.println("SocketException " + e);
 }
 catch(IOException e)
 {
  System.out.println("IOException " + e);
 }

  // Finally closing the socket from 
  the client side

 finally
 {
 try
  {
   sock.close();
  }
  catch(IOException ie)
  {
   System.out.println(" Close Error   :" + 
   ie.getMessage());
  }               
 }  // finally 
                        
} // main 
}   // Class Client 
 

Running the Server and Client

After you've successfully compiled the server and the client programs, you run them. You have to run the server program first. Just use the Java interpreter and specify the Server class name. Once the server has started, you can run the client program. After the client sends a request and receives a response from the server, you should see output similar to this :
On client side:
   Hello from Server
On Server side:
   Hi from client

Connectionless Client and Server : (UDP)

A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed.
The java.net package contains two classes to help you write Java programs that use datagrams to send and receive packets over the network: DatagramSocket, DatagramPacket, and MulticastSocket An application can send and receive DatagramPackets through a DatagramSocket. In addition, DatagramPackets can be broadcast to multiple recipients all listening to a MulticastSocket.
The following source code demonstrates a slightly more complex server that uses datagrams instead of sockets. After a connection is made, It echoes back whatever is sent by the client instead of simply hanging up the connection. It is Called as echo Server.

Server Program

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


public class EchoServer
{

//Initialize Port number and Packet Size
  
 static final int serverPort = 1026;
 static final int packetSize = 1024;

 public static void main(String args[]) 
 throws SocketException{

 DatagramPacket packet;
 DatagramSocket socket;
 byte[] data;    // For data to be 
 Sent in packets
 int clientPort;
 InetAddress address;
 String str;

 socket = new DatagramSocket(serverPort);

 for(;;){
 data = new byte[packetSize];

 // Create packets to receive the message

 packet = new DatagramPacket(data,packetSize); 
 System.out.println("Waiting to receive 
 the packets");

 try{

 // wait infinetely for arrive of the packet

 socket.receive(packet);

 }catch(IOException ie)
 {
 System.out.println(" Could not Receive
 :"+ie.getMessage());
 System.exit(0);
 }
  
 // get data about client in order to 
 echo data back
  
 address = packet.getAddress();
 clientPort = packet.getPort();
  
 // print string that was received 
 on server's console
 str = new String(data,0,0,packet.getLength());
 System.out.println("Message  :"+ str.trim());
 System.out.println("From   :"+address);
  
 // echo data back to the client 
 // Create packets to send to the client
  
 packet = new DatagramPacket(data,packetSize,
 address,clientPort);
  
 try
 {
 // sends packet   

 socket.send(packet);

 }
 catch(IOException ex)
 {
  System.out.println("Could not Send 
  "+ex.getMessage());
  System.exit(0);
  }
  
 } // for loop

 } // main


} // class EchoServer

Client Program

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


public class EchoClient{
   
 static final int serverPort = 1026;
 static final int packetSize = 1024;
   
 public static void main(String args[]) throws
 UnknownHostException, SocketException{
 DatagramSocket socket; //How we send packets
 DatagramPacket packet; //what we send it in
 InetAddress address; //Where to send
 String messageSend; //Message to be send
 String messageReturn; //What we get back 
 from the Server
 byte[] data;
       
 //Checks for the arguments that sent to 
 the java interpreter
 // Make sure command line parameters correctr
       
 if(args.length != 2)
 {
 System.out.println("Usage Error :
 Java EchoClient < Server name> < Message>");
 System.exit(0);
 }   
       
 // Gets the IP address of the Server
 address = InetAddress.getByName(args[0]);
 socket = new DatagramSocket();
               
 data = new byte[packetSize];
 messageSend = new String(args[1]);
 messageSend.getBytes
 (0,messageSend.length(),data,0);
               
 // remember datagrams hold bytes
 packet = new
 DatagramPacket(data,data.length,address,serverPort);
 System.out.println(" Trying to Send the packet ");
               
 try
 {
  // sends the packet
               
  socket.send(packet);
           
  }
  catch(IOException ie)
  {
  System.out.println("Could not Send :"+ie.getMessage());
  System.exit(0);
  }            
       
  packet is reinitialized to use it for recieving
       
  packet = new DatagramPacket(data,data.length);
               
  try
  {
  // Receives the packet from the server
                   
  socket.receive(packet);   
               
  }
  catch(IOException iee)
  {
  System.out.println("Could not receive :
  "+iee.getMessage() );
  System.exit(0);
  }       
       
  // display message received
       
  messageReturn = new String (packet.getData(),0);
  System.out.println("Message Returned : "+
  messageReturn.trim());
  }    // main
   
   
 } // Class EchoClient

Running the Server and Client

The client side and the server side networking code looks actually very similar.This is true with many applications that use datagrams because the java.net.DatagramSocket class is used to both send and receive DatagramPackets.
Suppose server running on the machine named Hari.calsoftlabs.com, whereas the client running on the xxxx.info.com. As you can see at the end of the example the server is running waiting for the another connection, while the execution of the client has halted.
Server Side :
To start the server :
Java EchoServer
Output:
Message:Hello
From   :xxxx.info.com
Client Side :
Java EchoClient abhishek-bit.blogspot.com Hello
Output:
Message Returned : Hello

2 comments:

ramendra said...

brother there are 15 errors in server's code and 34 errors in client's code.please debug it....

Anonymous said...

Bro this code is SHIT