/* Implementation of Socket Programming Using UDP */
// UDPServer.java : A Simple UDP Server Program
import java.io.*;
import java.net.*;
import java.util.*;
public class UDPServer
{
public static void main(String args[]) throws Exception
{
try
{
Date d = new Date();
byte[] Message = d.toString().getBytes();
int Port;
BufferedReader Buf =new BufferedReader(new
InputStreamReader(System.in));
System.out.print(" Enter the Port Address : " );
Port=Integer.parseInt(Buf.readLine());
DatagramSocket ds = new DatagramSocket(4343);
DatagramPacket dp = new DatagramPacket(Message,
Message.length,InetAddress.getLocalHost(),Port);
ds.send(dp);
System.out.println(" Message Send Successfully. ");
ds.close();
}
catch(Exception e)
{
System.out.println(" Error : " + e.getMessage());
}
}
}
// UDPClient.java : A Simple UDP Client Program
import java.net.*;
import java.util.*;
import java.io.*;
public class UDPClient
{
public static void main(String args[]) throws IOException
{
try
{
byte Message[] = new byte[2024];
int Port;
BufferedReader Buf =new BufferedReader(new
InputStreamReader(System.in));
System.out.print(" Enter the Port Address : " );
Port=Integer.parseInt(Buf.readLine());
DatagramSocket ds = new DatagramSocket(Port);
System.out.println(" Client is Ready To Receive a Message. ");
System.out.println(" Waiting ..... ");
DatagramPacket dp = new
DatagramPacket(Message,Message.length);
ds.receive(dp);
byte[] info=dp.getData();
System.out.println(" Message Received From Server. ");
// System.out.println(" The Current Server Time is : " + new
String(dp.getData(),0,dp.getLength()));
System.out.println(" The Current Server Time is : " + new
String(info,0,dp.getLength()));
ds.close();
}
catch(Exception e)
{
System.out.println(" Error : " + e.getMessage());
}
}
}
OUTPUT :
UDPServer.java :
javac UDPServer.java
java UDPServer
Enter the Port Address : 1234
Message Send Successfully.
UDPClient.java :
javac UDPClient.java
java UDPClient
Enter the Port Address : 1234
Client is Ready To Receive a Message.
Waiting .....
Message Received From Server.
The Current Server Time is : Thu Sep 02 20:46:14 IST 2010
No comments:
Post a Comment