2017-02-01 383 views
-3

每次我運行客戶端時,服務器都會告訴我一個不同的端口號。我搜查了一下,發現當我將端口設置爲零時,它會查找可用端口,但我將其更改爲我想要的號碼public static final int MYPORT = 5555;,並且每次都從服務器獲取新的端口號。如何在java中的udp(client,server)程序中設置客戶端的端口號?

這是打印方法:

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])); 
+1

嘗試後(和縮進)你的代碼更相關的部分。 – freedev

+0

添加它在您的文章,而不是在評論:) – freedev

+0

它已被編輯,你知道答案嗎? – Sam

回答

0

我想你忽略了一點,這段代碼偵聽端口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