C# UDP 服务器/客户端 - NAT

发布于 2025-01-08 03:53:29 字数 3154 浏览 1 评论 0原文

我正在尝试从客户端向服务器发送消息(通过 UDP)。服务器应该回答这个消息,如果客户端收到这个答案,他应该打印出一条消息。

如果我在本地网络上运行客户端和服务器,一切正常。 如果我尝试从网络外部的另一台电脑通过互联网进行连接,服务器会收到客户端的请求,发回答案,但客户端永远不会收到此答案。客户端和服务器都位于 NAT 之后,但我将服务器 NAT 上的端口进行端口转发,并且服务器拥有自己的 DNS。我已经尝试过 NAT 穿越,但在收到客户端的请求后,它给我的 IP 和端口地址与服务器的 IPEndPoint 相同。

我不知道如何解决这个问题,所以任何指导将不胜感激。

客户端和

public static void Main()
{
    Thread receiveThread = new Thread(new ThreadStart(ReceiveData));
    receiveThread.Start();

    object[] oData = {1};
    sendData(oData, 0,0, "Li"); 

    while (true)
    {
        Console.ReadLine();
    }
}


private void receiveData()
{
    string receivePort = 8080;

    Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    client.ReceiveTimeout = 1000;
    IPEndPoint end = new IPEndPoint(IPAddress.Any, receivePort);
    client.Bind(end);


    while (true)
    {
        try
        {
            byte[] data = new byte[1024];

            client.Receive(data, 0, data.Length, SocketFlags.None);

            object[] receivedObj = Deserialize(data);

            string sType = (string)receivedObj[3];

            if (sType == "Li")
            {
           console.WriteLine("received Li");
            }
         }
         catch (Exception err)
         {
                Console.WriteLine(err.ToString());
         }
     }
}

public static void sendData(object[] oData, int iFrom, int iTo, string sType)
{
    string sendPort = 17171;

    UdpClient client = new UdpClient();

    string IP = "ThisIsTheDNSofmyServer.com"; //ServerDNS
    //string IP = "192.168.xxx.xxx"; //serverIP in LAN 

    if (IP.StartsWith("T")) 
    {
        IP = (Dns.GetHostAddresses(IP))[0].ToString();
    }

    IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), sendPort);

    oData[1] = iFrom;
    oData[2] = iTo;
    oData[3] = sType;

    Byte[] data = Serialize(oData);
    client.Send(data, data.Length, remoteEndPoint);

}

服务器端的代码几乎是一样的:

public static void Main()
{
    Thread receiveThread = new Thread(new ThreadStart(ReceiveData));
    receiveThread.Start();

    while (true)
    {
        Console.ReadLine();
    }
}

private static void ReceiveData()
{
    int receivePort = 17171;
    UdpClient client = new UdpClient(receivePort);

    while (true)
    {
        try
        {
            IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
            byte[] data = new byte[1024];

            data = client.Receive(ref anyIP);

            object[] receivedObj = Deserialize(data);

            //if I receive data send an Answer
            sendData(receivedObj, 0,0,"Li",anyIP.Address.ToString()); 

        }
        catch (Exception err)
        {
            Console.WriteLine(err.ToString());
        }
    }
}

private static void sendData(object[] oData, int iFrom, int iTo, string sType, string IP)
{
    int sendPort = 8080;
    object[] paket = { oData, iFrom, iTo, sType };

    UdpClient client = new UdpClient();

    IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), sendPort); 

    client.Send(data, data.Length, remoteEndPoint);

 }

Iam trying to send a message (via UDP) from my client to my server. The server should answer this message and if the client receives this answer he should print out a message.

If i run the client and server on my local network everything works fine.
If i try to connect through the internet from another PC outside my network the server receives the request of the client, sends an answer back, but the client never receives this answer. The client and the server are both behind a NAT but i portforwarded the ports at the server´s NAT and the server got its own DNS. I already tried NAT traversal but it gives me the same IP and port adress as the IPEndPoint of the server, after receiveing the request of the client, does.

I´ve got no idea how to fix this, so any guidance would be much appreciated.

Client

public static void Main()
{
    Thread receiveThread = new Thread(new ThreadStart(ReceiveData));
    receiveThread.Start();

    object[] oData = {1};
    sendData(oData, 0,0, "Li"); 

    while (true)
    {
        Console.ReadLine();
    }
}


private void receiveData()
{
    string receivePort = 8080;

    Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    client.ReceiveTimeout = 1000;
    IPEndPoint end = new IPEndPoint(IPAddress.Any, receivePort);
    client.Bind(end);


    while (true)
    {
        try
        {
            byte[] data = new byte[1024];

            client.Receive(data, 0, data.Length, SocketFlags.None);

            object[] receivedObj = Deserialize(data);

            string sType = (string)receivedObj[3];

            if (sType == "Li")
            {
           console.WriteLine("received Li");
            }
         }
         catch (Exception err)
         {
                Console.WriteLine(err.ToString());
         }
     }
}

public static void sendData(object[] oData, int iFrom, int iTo, string sType)
{
    string sendPort = 17171;

    UdpClient client = new UdpClient();

    string IP = "ThisIsTheDNSofmyServer.com"; //ServerDNS
    //string IP = "192.168.xxx.xxx"; //serverIP in LAN 

    if (IP.StartsWith("T")) 
    {
        IP = (Dns.GetHostAddresses(IP))[0].ToString();
    }

    IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), sendPort);

    oData[1] = iFrom;
    oData[2] = iTo;
    oData[3] = sType;

    Byte[] data = Serialize(oData);
    client.Send(data, data.Length, remoteEndPoint);

}

The server´s code is almost the same:

public static void Main()
{
    Thread receiveThread = new Thread(new ThreadStart(ReceiveData));
    receiveThread.Start();

    while (true)
    {
        Console.ReadLine();
    }
}

private static void ReceiveData()
{
    int receivePort = 17171;
    UdpClient client = new UdpClient(receivePort);

    while (true)
    {
        try
        {
            IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
            byte[] data = new byte[1024];

            data = client.Receive(ref anyIP);

            object[] receivedObj = Deserialize(data);

            //if I receive data send an Answer
            sendData(receivedObj, 0,0,"Li",anyIP.Address.ToString()); 

        }
        catch (Exception err)
        {
            Console.WriteLine(err.ToString());
        }
    }
}

private static void sendData(object[] oData, int iFrom, int iTo, string sType, string IP)
{
    int sendPort = 8080;
    object[] paket = { oData, iFrom, iTo, sType };

    UdpClient client = new UdpClient();

    IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), sendPort); 

    client.Send(data, data.Length, remoteEndPoint);

 }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

謸气贵蔟 2025-01-15 03:53:29

我相信这是一个端口配置问题,

8080 几乎可能被配置为备用 http

“用于接收数据报的 UdpClient 必须使用多播端口号创建” 来自 MSDN

希望这有帮助,祝你好运

克里希纳

i believe this is a port cofniguration issue,

8080 is almost likely to be configured as alternate http

"The UdpClient you use to receive datagrams must be created using the multicast port number" from MSDN

Hope this helps and good luck

Krishna

故事灯 2025-01-15 03:53:29

在你描述的设置中,你不需要做任何不寻常的事情来穿越 NAT,你只需要把它从服务器发送回你的客户端;具体来说:您必须发送回端点,即您收到的 IP 端口。

client.Send(data, data.Length, remoteEndPoint); // remoteEndPoint is the IPEndPoint you got the datagram on

You do not need to do anything unordinary to traverse NAT in the setup you described, you just need to send it from the server back to your client; specifically: you must send back to the end point, i.e. IP and port, you received it on.

client.Send(data, data.Length, remoteEndPoint); // remoteEndPoint is the IPEndPoint you got the datagram on
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文