Sunday, 7 October 2012

Udp Client-Server Communication using java

UDP Client

import java.io.*;
import java.net.*;
class udpclient {
    public static void main(String args[])throws Exception
    {
       
        DatagramSocket cs = new DatagramSocket(2568);
        InetAddress ip = InetAddress.getByName("localhost");
        byte[] sD = new byte[1024];
        byte[] rD = new byte[1024];
 String sen;
        while(true)
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       sen= br.readLine();
      
       
        sD=sen.getBytes();
        DatagramPacket sPkt = new DatagramPacket(sD,sD.length,ip,6800);
        cs.send(sPkt);
        DatagramPacket rPkt = new DatagramPacket(rD,rD.length);
        cs.receive(rPkt);
        String str= new String(rPkt.getData());
        System.out.println("From Server:\n"+str);
        }
       
    }
   
}

UDP Server

import java.io.*;
import java.net.*;
class udpserver {
    public static void main(String args[])throws Exception
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        DatagramSocket cs = new DatagramSocket(6800);
       
        byte[] sD = new byte[1024];
        byte[] rD = new byte[1024];
        while(true)
        {
          DatagramPacket rPkt = new DatagramPacket(rD,rD.length);
        cs.receive(rPkt);
        String str= new String(rPkt.getData());
        System.out.println("From Client:\n"+str);
InetAddress ip = rPkt.getAddress();
int port = rPkt.getPort();  
        String sen= br.readLine();
       
       
        sD=sen.getBytes();
        DatagramPacket sPkt = new DatagramPacket(sD,sD.length,ip,port);
        cs.send(sPkt);
      
        }
       
    }
   
}

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More