Communication using DatagramSocket (UDP)
//Use udp to send messages
public class UDPMsgSender {
private static int port = 8000; //Need to change a port, not the same as tcp
public static void send(String msg, InetAddress host){
if(msg == null)
return;
System.out.println("服务端发送消息:"+msg);
try {
DatagramSocket socket = new DatagramSocket();
byte[] buf = msg.getBytes();
//DatagramPacket packet = new DatagramPacket(buf, buf.length); //java.lang.NullPointerException: null address
DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getByName("lenovo-PC"), port);
socket.send(packet);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
static class MessageReceiver implements Runnable{
public void run(){
DatagramSocket socket = null;
try {
socket = new DatagramSocket(8000);
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
while(true){
socket.receive(packet);
byte[] msg = packet.getData();
String msgStr = new String(msg);
System.out.println("接收服务端的消息:" + msgStr);
}
} catch (Exception e) {
e.printStackTrace();
}
socket.close();
}
}