下面有两个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