Write a UDP program for chat application.
import java.io.*;
import java.net.*;
import java.util.*;
class UDPClientChat {
public static void main(String[] args) {
try {
DatagramSocket dataSocket = new DatagramSocket(9876);
byte receiveByte[] = new byte[1024];
Scanner sc = new Scanner(System.in);
InetAddress ip = InetAddress.getByName("Localhost");
DatagramPacket dataRecPacket = new DatagramPacket(receiveByte, receiveByte.length);
while(true) {
receiveByte = null;
System.out.print("Client: ");
String sendMsg = sc.nextLine();
DatagramPacket dataSndPacket = new DatagramPacket(sendMsg.getBytes(), sendMsg.length(), ip, 9877);
dataSocket.send(dataSndPacket);
dataSocket.receive(dataRecPacket);
String clientMsg = new String(dataRecPacket.getData());
System.out.println("Server: " + clientMsg.trim());
}
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
UDP Server:
import java.io.*;
import java.net.*;
import java.util.*;
class UDPServerChat {
public static void main(String[] args) {
try {
DatagramSocket dataSocket = new DatagramSocket(9877);
byte receiveByte[] = new byte[1024];
Scanner sc = new Scanner(System.in);
InetAddress ip = InetAddress.getByName("Localhost");
DatagramPacket dataRecPacket = new DatagramPacket(receiveByte, receiveByte.length);
while(true) {
receiveByte = null;
dataSocket.receive(dataRecPacket);
String clientMsg = new String(dataRecPacket.getData());
System.out.println("Client: " + clientMsg.trim());
System.out.print("Server: ");
String sendMsg = sc.nextLine();
DatagramPacket dataSndPacket = new DatagramPacket(sendMsg.getBytes(), sendMsg.length(), ip, 9876);
dataSocket.send(dataSndPacket);
}
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
0 Comments