
[英]RTP, Media packets behind firewall and behind Nat makes life hard to fix it, now i am trying to do the UDP hole punching, to get ride of it
[英]I have been trying hole punching and send a datagram to my friends computer behind a router but nothing happens
我正在尝试创建p2p连接。 这是我已经检查过的只是一个测试应用程序,但似乎无法通过互联网运行。 这是我在PC上用来向我的朋友发送数据报的Java代码:
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.*;
import javax.net.ssl.SSLServerSocket;
public class j2{
public static void main(String[] args) throws Exception {
InetAddress IPAddress = InetAddress.getByName("my friend's public IP");
DatagramSocket clientSocket = new DatagramSocket(3456);
System.out.println("Sending data");
String datamsg = "hello ";
byte[] sendData = datamsg.getBytes("UTF-8");
byte [] receiveData = new byte[10];
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 7890);
int i = 500;
//incase if some packets are lost
while(i-->1)
{
clientSocket.send(sendPacket);
}
System.out.println("Data sent");
System.out.println(clientSocket.isClosed());
clientSocket.close();
}
}
'
//My friend uses this app to receive a data gram:
// port 7890 is used to send data gram and create a hole. The same is used to receice data.
'
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.*;
import javax.net.ssl.SSLServerSocket;
public class j1{
public static void main(String[] args) throws Exception {
InetAddress IPAddress = InetAddress.getByName("any ip"); //does not matter as it is used to open a hole
DatagramSocket clientSocket = new DatagramSocket(7890);
System.out.println("Sending data");
String datamsg = "hello ";
byte[] sendData = datamsg.getBytes("UTF-8");
byte [] receiveData = new byte[10];
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 5000);
int i = 500;
while(i-->1)
{
clientSocket.send(sendPacket);
}
System.out.println("Data sent");
System.out.println(clientSocket.isClosed());
DatagramPacket receivePacket = new DatagramPacket(sendData, sendData.length);
clientSocket.receive(receivePacket);
System.out.println("Packet received");
String msg = new String(receivePacket.getData());
clientSocket.close();
}
}'
// I am not using a stun server as i already know my friends public ip address. We both have disabled our firewall as well.
您的方法不是进行NAT打孔的最可靠方法。 充其量,它有时会“起作用”。
这里有一些建议:
不要硬编码端口号。 让您的UDP套接字代码选择一个随机端口号(即port = 0),然后使用STUN服务器(或等效服务器)来确定此本地套接字的公共IP地址和公共端口映射。
使用可靠的服务来交换IP /端口。 由于您只是想让单个数据包通过,因此从使用手机进行语音信息交换开始就足够了。
您无需一次发送500个数据包。 远程NAT上的防火墙代码可能会将其视为DOS攻击并阻止所有内容。 尝试每秒发送1次。
尝试执行代码正在执行的连接检查时,您应该同时侦听并发送定期数据包。 (例如,两个单独的线程或定期轮询)。
在两个端点都确认连通性之前,不要关闭套接字。 现在,您的第一个程序在发送数据包突发后立即关闭套接字。
在这里阅读我的完整答案: https : //stackoverflow.com/a/8524609/104458
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.