Tuesday, May 29, 2012

Datagram Client in Java

This Example is implementation of Datagram Client or UDP client purpose of this example is to provide a fare idea about the working of UDP client server this client example works with server example and link to server example is given at the end of this code example works on the concept of UDP protocol (simple transmission model without implicit handshaking)

import java.io.*;

import java.net.*;

public class Client {

    public static void main(String[] args) {

      DatagramSocket clientSkt = null;

      InetAddress IPAdd = null;

      String text =null;

      DatagramPacket receivePkt= null;

      BufferedReader inFromUser =

         new BufferedReader(new InputStreamReader(System.in));

      try{

      clientSkt = new DatagramSocket();

      IPAdd = InetAddress.getByName("localhost");

      }

      catch(SocketException exp){

          System.out.println(exp);

      }

      catch(UnknownHostException exp){

          System.out.println(exp);

      }      

      byte[] sendData = new byte[1024];

      byte[] receiveData = new byte[1024];

      try{

      text = inFromUser.readLine();

      sendData = text.getBytes();

      DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAdd, 3030);

      clientSkt.send(sendPacket);

      receivePkt = new DatagramPacket(receiveData, receiveData.length);

      clientSkt.receive(receivePkt);

      }

      catch(IOException exp){

          System.out.println(exp);

      }

      String modifiedSentence = new String(receivePkt.getData());

      System.out.println("FROM SERVER:" + modifiedSentence);

      clientSkt.close();

    }

}

Datagram Server Source

2 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete