Sunday, June 24, 2012

44.UDP PROTOCOL IN JAVA


Server Program:

import java.io.*;
import java.net.*;
public class Server
{
public static void main(String str1[]) throws Exception
{
DatagramSocket ds;
byte[] buf=new byte[1024];
ds=new DatagramSocket(200);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“Enter the String”);
InetAddress ia=InetAddress.getLocalHost();
while(true)
{

String str=new String();
str=br.readLine();
buf=str.getBytes();
DatagramPacket dp=new DatagramPacket(buf,buf.length,ia,300);
ds.send(dp);
if(str.equals(“ends”))
break;
}
}
}


Client Program

import java.io.*;
import java.net.*;
public class Client
{
public static void main(String asd[]) throws Exception
{
byte[] buf=new byte[1024];
DatagramSocket ds=new DatagramSocket(300);
DatagramPacket dp=new DatagramPacket(buf,buf.length);
boolean b=true;
while(true)
{
ds.receive(dp);
buf=dp.getData();
String str=new String(buf,0,dp.getLength());
if(str.equals(“ends”))
break;
System.out.println(str);
}
}
}