1a Udp
1a Udp
1a Udp
java
import java.net.*;
import java.io.*;
import java.util.*;
import java.lang.*;
public class UDPClient
{
public static void main(String args[])
{
// args give message contents and server hostname
String m1;
DatagramSocket aSocket = null;
try
{
do
{
Scanner in = new Scanner(System.in);
System.out.print("Enter Message: ");
String msg = in.nextLine();
byte [] m = msg.getBytes();
aSocket = new DatagramSocket();
InetAddress aHost = InetAddress.getByName(args[0]);
int serverPort = 6678;
DatagramPacket request = new DatagramPacket(m, m.length,
aHost, serverPort);
aSocket.send(request);
byte[] buffer = new byte[1000];
DatagramPacket reply = new DatagramPacket(buffer,
buffer.length);
aSocket.receive(reply);
m1=new String(reply.getData());
System.out.println("Server Send: " + new
String(reply.getData()));
}while(true);
} catch (SocketException e)
{
System.out.println("Socket: " + e.getMessage());
} catch (IOException e)
{
System.out.println("IO: " + e.getMessage());
} finally
{
if(aSocket != null)
aSocket.close();
}
}
}
UDPServer.java
import java.net.*;
import java.io.*;
import java.util.*;
public class UDPServer
{
public static void main(String args[])
{
DatagramSocket aSocket = null;
try
{
aSocket = new DatagramSocket(6678);
byte[] buffer = new byte[1000];
while(true)
{
Scanner in = new Scanner(System.in);
DatagramPacket request = new DatagramPacket(buffer,
buffer.length);
aSocket.receive(request);
System.out.println("Client Send: " + new
String(request.getData()));
System.out.print("Enter Message: ");
String msg = in.nextLine();
byte [] m = msg.getBytes();
DatagramPacket reply = new DatagramPacket(m, m.length,
request.getAddress(), request.getPort());
aSocket.send(reply);
}
} catch (SocketException e)
{
System.out.println("Socket: " + e.getMessage());
} catch (IOException e)
{
System.out.println("IO: " + e.getMessage());
} finally
{
if (aSocket != null)
aSocket.close();
}
}
}
OUTPUT:
UDP Client
info-13@info13-OptiPlex-3020:~$ cd Desktop
info-13@info13-OptiPlex-3020:~/Desktop$ javac UDPClient.java
info-13@info13-OptiPlex-3020:~/Desktop$ java UDPClient 127.0.0.1
Enter Message: Hello
Server Send: Hi!
Enter Message: What's up?
Server Send: Nothing much. You?
Enter Message: Same. Wanna go for a movie?
Server Send: Sure. Which?
Enter Message: URI
Server Send: Sure. I will book the tickets!
Enter Message: See you
UDPServer
info-13@info13-OptiPlex-3020:~$ cd Desktop
info-13@info13-OptiPlex-3020:~/Desktop$ javac UDPServer.java
info-13@info13-OptiPlex-3020:~/Desktop$ java UDPServer
Client Send: Hello
Enter Message: Hi!
Client Send: What's up?
Enter Message: Nothing much. You?
Client Send: Same. Wanna go for a movie?
Enter Message: Sure. Which?
Client Send: URIe. Wanna go for a movie?
Enter Message: Sure. I will book the tickets!
Client Send: See youanna go for a movie?
Enter Message