Use DatagramSocket to send out and receive DatagramPacket
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class ChatClient {
public static void main(String[] args) throws Exception {
DatagramSocket s = new DatagramSocket();
byte[] buf = new byte[1000];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
InetAddress hostAddress = InetAddress.getByName("localhost");
while (true) {
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String outMessage = stdin.readLine();
if (outMessage.equals("bye"))
break;
String outString = "Client say: " + outMessage;
buf = outString.getBytes();
DatagramPacket out = new DatagramPacket(buf, buf.length, hostAddress, 9999);
s.send(out);
s.receive(dp);
String rcvd = "rcvd from " + dp.getAddress() + ", " + dp.getPort() + ": "
+ new String(dp.getData(), 0, dp.getLength());
System.out.println(rcvd);
}
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class ChatServer {
public static void main(String[] args) throws Exception {
int PORT = 4000;
byte[] buf = new byte[1000];
DatagramPacket dgp = new DatagramPacket(buf, buf.length);
DatagramSocket sk;
sk = new DatagramSocket(PORT);
System.out.println("Server started");
while (true) {
sk.receive(dgp);
String rcvd = new String(dgp.getData(), 0, dgp.getLength()) + ", from address: "
+ dgp.getAddress() + ", port: " + dgp.getPort();
System.out.println(rcvd);
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String outMessage = stdin.readLine();
buf = ("Server say: " + outMessage).getBytes();
DatagramPacket out = new DatagramPacket(buf, buf.length, dgp.getAddress(), dgp.getPort());
sk.send(out);
}
}
}
Related examples in the same category