我正在尝试使用UDP打孔来进行voip应用程序。我目前正在使用这部分:
现在我在最后阶段遇到了麻烦,这是我目前的代码。我遇到的问题是,虽然我们彼此拥有其他人。 ip地址和端口我们无法互相连接p2p。有没有人有任何建议?
ContactPort =从服务器返回的contactsPort
private void PunchHole()
{
try
{
int range = 10000;
if ((contactPort - range) < 1000) { contactPort = (contactPort + (range * 2)); }
//else if ((contactPort + range) >= 65535) { range = range / 2; }
int port = (contactPort - range);
byte[] bytesToSend = Encoding.UTF8.GetBytes("Stop");
#region Punch hole through different ports - for loop
//Console.WriteLine(port);
for (int i = (contactPort - range); i < 65534; i++)
{
if (punchingHole)
{
udpClient.Send(bytesToSend, bytesToSend.Length, contactIP.ToString(), port);
port++;
}
else { break; }
}
if (port >= 65533 && punchingHole)
{
range = range * 2;
port = contactPort - range;
if (port < 1000) { port = contactPort - (range / 2); }
for (int i = port; i < 65534; i++)
{
if (punchingHole)
{
udpClient.Send(bytesToSend, bytesToSend.Length, contactIP.ToString(), port);
port++;
if (port >= 65533 && (contactPort + 1000) > range) { port = contactPort - range; i = port; continue; }
}
else { break; }
}
}
if (punchingHole)
{
Console.WriteLine("Hole punch unsucessful.");
}
#endregion
}
catch (SocketException sockEx) { if (sockEx.SocketErrorCode == SocketError.Interrupted) { }
else { MessageBox.Show(sockEx.Message, "PunchHole()"); } }
catch (Exception ex) { MessageBox.Show(ex.Message, "PunchHole()");}
}
private void ListeningPort()
{
Console.WriteLine("Started Listening");
IPEndPoint listenEP = new IPEndPoint(IPAddress.Any, localPort);
byte[] messageBytes = udpClient.Receive(ref listenEP);
punchingHole = false;
voiceCallEP = new IPEndPoint(listenEP.Address, listenEP.Port);
message = Encoding.UTF8.GetString(messageBytes);
Console.WriteLine(message);
Console.WriteLine(listenEP.Address.ToString().PadRight(30) + listenEP.Port);
udpClient.Send(messageBytes, messageBytes.Length, voiceCallEP);
this.Invoke(new MethodInvoker(delegate() { label1.Text = "Hole punched succesfully."; }));
InitialiseCall();
}
答案 0 :(得分:0)
您不必扫描所有65535端口。您可能会发现,如果您这样做,某些防火墙会阻止您。您的服务器应告知client1 client2的终点(公共IP和端口),反之亦然。
随意在这里使用我的例子: https://github.com/7wingfly/P2Pchat