下面有兩個Groovy子程序通過普通的UDP套接字向對方發送消息。當他們發送到127.0.0.1
時,他們確實收到消息。但是,將消息發送到公共IP地址時(該機器位於NAT後面)未收到消息。爲什麼UDP打孔不能用於公共IP地址?
爲什麼不打孔?以及如何解決這個問題?
我試過早期通過Java庫查詢公共STUN服務器,但它使用相同的公共IP地址給我回應,所以我在這裏使用wtfismyip.com
。
class GroovyTest {
static String PUBLIC_IP = new URL('https://wtfismyip.com/text').text.trim()
//static String PUBLIC_IP = '127.0.0.1' // works fine
static void main(String[] args) {
runInstance(11111, 22222)
runInstance(22222, 11111)
}
static void runInstance(int thisPort, int anotherPort) {
def socket = new DatagramSocket(thisPort)
Thread.start {
// message listener
byte[] buf = new byte[1024]
while (true) {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
InetAddress remoteAddr = packet.getAddress();
int remotePort = packet.getPort();
String sentence = new String(packet.getData(), 0, packet.length);
println("server-$thisPort: received [$sentence] from ${remoteAddr.hostAddress}:${remotePort}")
}
}
Thread.start {
// message sender
while (true) {
println("client-$thisPort: sending to ${PUBLIC_IP}:${anotherPort}...")
byte[] buf = ("Hello " + System.currentTimeMillis()).bytes
DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getByName(PUBLIC_IP), anotherPort)
socket.send(packet)
Thread.sleep(2000)
}
}
}
}
'new URL('https://wtfismyip.com/text').text.trim()' - 真的嗎? –
@shmosel哦Groovy –
https://stackoverflow.com/a/8524609/104458 – selbie