每次我运行客户端时,服务器都会告诉我一个不同的端口号。我搜索了一下,发现当我将端口设置为零时,它会查找可用端口,但我将其更改为我想要的数字public static final int MYPORT = 5555;
,并且每次都从服务器获取新的端口号。
这是打印方法:
System.out.printf(" using port %d\n", receivePacket.getPort());
DatagramSocket socket = new DatagramSocket(null);
SocketAddress localBindPoint = new InetSocketAddress(MYPORT); socket.bind(localBindPoint);
SocketAddress remoteBindPoint = new InetSocketAddress(args[0], Integer.valueOf(args[1]));
答案 0 :(得分:1)
我认为你错过了这一点,这段代码在端口5555上侦听:
以下代码中的istruction packet.getPort()
返回发送此数据报或从中接收数据报的远程主机上的端口号。
int MYPORT = 5555;
DatagramSocket dsocket = new DatagramSocket(MYPORT);
byte[] buffer = new byte[2048];
// Create a packet to receive data into the buffer
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
// Wait to receive a datagram
dsocket.receive(packet);
// Convert the contents to a string, and display them
String msg = new String(buffer, 0, packet.getLength());
System.out.println(packet.getAddress().getHostName() + ": "
+ msg);
// Reset the length of the packet before reusing it.
packet.setLength(buffer.length);
System.out.printf(" using port %d\n", packet.getPort());
}
我在本地进行了双重检查:
sudo lsof -iUDP -n -P | grep 5555
java 1606 freedev 5u IPv6 0x9ed7290ce134656f 0t0 UDP *:5555