c# - UDP over NAT(通过互联网)
问题描述
我正在编写一个带有服务器(在 NAT 后面,带有 UDP 端口转发、静态白色 IP)和客户端(在 NAT 后面,没有任何自定义设置)的系统。
任务是通过 Internet 从服务器向客户端发送数据。为了让服务器知道客户端的端点(客户端的路由器保存转换表),客户端每 5 秒向服务器发送一次简单的 UDP 请求,如“Hello!”。服务器代码:
private void SendData(ref string destination, CancellationToken cancelToken)
{
UdpClient senderClient = new UdpClient(AddressFamily.InterNetwork);
try
{
while (true)
{
cancelToken.ThrowIfCancellationRequested();
if (string.IsNullOrEmpty(destination))
continue;
byte[] testMessage = Encoding.UTF8.GetBytes("AnyDatas");
string ip = destination.Split(':')[0];
string p = destination.Split(':')[1];
IPEndPoint clientEP = new IPEndPoint(IPAddress.Parse(ip), int.Parse(p));
senderClient.Send(testMessage, testMessage.Length, clientEP);
Thread.Sleep(3000);
}
}
catch (OperationCanceledException ex)
{ }
finally
{
if (senderClient != null)
senderClient.Close();
}
}
private void ListenConnectionSupport(ref string stClientEP, CancellationToken cancelToken)
{
IPEndPoint IpEp = new IPEndPoint(IPAddress.Any, 13001);
UdpClient listenClient = new UdpClient(IpEp);
try
{
while (true)
{
cancelToken.ThrowIfCancellationRequested();
IPEndPoint cIpEp=null;
byte[] messageBytes = listenClient.Receive(ref cIpEp);
if (Encoding.UTF8.GetString(messageBytes) == "UDP-support")
{
stClientEP = String.Format("{0}:{1}",cIpEp.Address,cIpEp.Port);
}
}
}
catch (OperationCanceledException ex)
{ }
finally
{
if (listenClient != null)
listenClient.Close();
}
}
这甚至有效!但仅当客户端在同一路由器下时,尽管向外部服务器 IP 发送客户端->服务器请求。
我像客户端路由器一样使用我的智能手机,然后重试(客户端是另一台 PC)。但是,虽然服务器得到了 Hello-request 并发送了应答,但是客户端什么也没得到。
更新 - - - - - - - - -
我需要为方案开发系统:服务器(192.168.0.3)-routerA(静态公共IP,具有服务器端口转发)-INTERNET-routerB(任何常规热点或路由器)-客户端
算法:
客户端向 routerA(在此上下文中 routerA=Server)发送“你好,给我你的数据”。对于路由器表客户端连续发送。
来自先前消息的服务器(如 STUN 服务器)可以记录客户端 EP。
WHILE(true) 循环中的服务器向客户端发送数据。
错误是“客户端没有从服务器获取数据”。
如果这很重要
服务器监听13001端口,客户端知道这个端口号
在“一个路由器案例”案例中,服务器看到客户端的端点,如“192.168.0.5”(他的本地 IP),在“两个路由器”案例中,客户端的端点看起来像未知 IP(我不知道那是什么,他的 ipconfig 显示另一个)。
请告诉我正确的方向!
解决方案
推荐阅读
- c# - google oAuth 尝试重定向到与我的应用程序 url 不同的随机 uri
- javascript - 为什么按引用传递似乎在这段代码中不起作用,而 obj1.value 仍然是函数的外部
- excel - 使用单元格 B3 中的日期值重命名工作簿中的多个工作表
- .net-core - 如何将 EWS API 与 Console App Net Core 一起使用
- electron - 可以在“开发模式”中写入文件,但不能在电子中写入“分布式模式”
- google-cloud-platform - 带有 TCP 负载均衡器的 Cloud VPN
- javascript - 纸张自动完成未显示任何结果
- javascript - 如何在请求节点js库中传递cookie
- ios - 如何在应用程序顶部显示状态栏?
- scala - 如何使用 Spark Structure Streaming 的 writeStream() 方法获取在本地系统中生成的 .csv 文件列表