【问题标题】:How to set the port number for the client in udp (client ,server) program in java?java - 如何在java中的udp(客户端,服务器)程序中为客户端设置端口号?
【发布时间】:2017-02-01 10:24:33
【问题描述】:

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

【问题讨论】:

  • 尝试发布(并缩进)代码中更相关的部分。
  • 将其添加到您的帖子中,而不是在 cmets 中 :)
  • 已编辑,你知道答案吗?
  • 我添加了一个代码示例来解释如何监听端口5555。你有什么:Mac、Linux、Windows?

标签: java sockets network-programming udp serversocket


【解决方案1】:

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

以下代码中的指令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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    • 1970-01-01
    • 2015-02-19
    相关资源
    最近更新 更多