UDP_Server.java
import java.net.*;
import java.io.*;
public class UDP_Server {
public static void main(String args[]) {
DatagramSocket dgSocket = null;
if (args.length < 1) {
System.out.println("UDP_Server");
System.exit(1);
}
try {
int socket_no = Integer.valueOf(args[0]).intValue();
dgSocket = new DatagramSocket(socket_no);
byte[] buffer_array = new byte[1000];
while (true) {
DatagramPacket request = new DatagramPacket(buffer_array, buffer_array.length);
dgSocket.receive(request);
DatagramPacket reply = new DatagramPacket(request.getData(), request.getLength(), request.getAddress(), request.getPort());
dgSocket.send(reply);
}
} catch (SocketException e) {
System.out.println("Socket : " + e.getMessage());
} catch (IOException e) {
System.out.println("i/o: " + e.getMessage());
} finally {
if (dgSocket != null) {
dgSocket.close();
}
}
}
}
UDP_Client.java
import java.net.*;
import java.io.*;
public class UDP_Client {
public static void main(String args[]) {
DatagramSocket dgSocket = null;
if (args.length < 3) {
System.out.println("UDP_Client ");
System.exit(1);
}
try {
dgSocket = new DatagramSocket();
byte[] m = args[0].getBytes();
InetAddress hostAdr = InetAddress.getByName(args[1]);
int serverPort = Integer.valueOf(args[2]).intValue();
DatagramPacket request
= new DatagramPacket(m, args[0].length(), hostAdr, serverPort);
dgSocket.send(request);
byte[] buffer = new byte[1000];
DatagramPacket dgRreply = new DatagramPacket(buffer, buffer.length);
dgSocket.receive(dgRreply);
System.out.println("Reply: " + new String(dgRreply.getData()));
} catch (SocketException e) {
System.out.println("Socket: " + e.getMessage());
} catch (IOException e) {
System.out.println("i/o " + e.getMessage());
} finally {
if (dgSocket != null) {
dgSocket.close();
}
}
}
}
No comments:
Post a Comment