java如何在udp(client,server)程序中为客户端设置端口号?

How to set the port number for the client in udp (client ,server) program in java?

每次我运行客户端服务器告诉我一个不同的端口号。我对此进行了搜索,发现当我将端口设置为零时,它会寻找一个可用端口,但我将其更改为我想要的数字 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]));

我想你没抓住要点,这段代码在端口 5555 上监听:

以下代码中的指令 packet.getPort() returns 正在将此数据报发送到或从中接收数据报的远程主机上的端口号。

  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