基本上我想做的是用4个客户端和1个服务器模拟一个应用程序,但我只有一台计算机这样做。
我创建了两个环回适配器169.254.153.173(服务器)和169.254.168.136(客户端)进行测试。
public class Server {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(9001, InetAddress.getByName("169.254.153.173"));
System.out.println(socket.getLocalAddress().getHostAddress());
System.out.println();
byte[] buf = new byte[1];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
System.out.println(packet.getAddress());
System.out.println(packet.getPort());
System.out.println(buf[0]);
System.out.println();
socket.close();
}
}
public class Client {
public static void main(String[]args) throws Exception {
DatagramSocket socket = new DatagramSocket(9000, InetAddress.getByName("169.254.168.136"));
System.out.println(socket.getLocalAddress().getHostAddress());
byte[] buf = {42};
DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getByName("169.254.153.173"), 9001);
socket.send(packet);
socket.close();
}
}
不幸的是,即使代码看起来很好,我的服务器也永远不会收到数据包。我知道它使用localhost工作,但这不是我想要的,因为我想将ip绑定到套接字,就像它在另一台计算机上一样。