test nat 打洞
import lombok.extern.slf4j.Slf4j;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
@Slf4j
public class UdpMain {
public static void main(String[] args) {
String targetIp = "182.239.92.228";//hk
int port = 9294;
try(DatagramSocket socket = new DatagramSocket(port)) {
InetSocketAddress target = new InetSocketAddress(targetIp,port);
DatagramPacket sendPacket = new DatagramPacket(new byte[1024],1024,target);
DatagramPacket receivePacket = new DatagramPacket(new byte[1024],1024);
//打洞
sendPacket.setData("ping".getBytes());
socket.send(sendPacket);
new Thread(() -> {
try {
sendPacket.setData("1".getBytes());
socket.send(sendPacket);
}catch (Exception e) {
log.error(e.getMessage());
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
while (true) {
socket.receive(receivePacket);
String content = new String(receivePacket.getData(),receivePacket.getOffset(),receivePacket.getLength());
log.info(content);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
不积跬步无以至千里