首页 > 解决方案 > 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(任何常规热点或路由器)-客户端

算法:

  1. 客户端向 routerA(在此上下文中 routerA=Server)发送“你好,给我你的数据”。对于路由器表客户端连续发送。

  2. 来自先前消息的服务器(如 STUN 服务器)可以记录客户端 EP。

  3. WHILE(true) 循环中的服务器向客户端发送数据。

错误是“客户端没有从服务器获取数据”。

如果这很重要

请告诉我正确的方向!

标签: c#udpnat

解决方案


推荐阅读