如何使用私有IP向客户端发送数据包?

时间:2018-06-27 08:47:20

标签: server udp client nat packets

我用c#制作客户端和服务器,我想在这2个应用程序之间发送数据包。当客户端向服务器发送消息时,一切正常,服务器将接受它。但是当服务器尝试答复时,客户端不会收到消息。我认为,这是有问题的,因为我有专用IP(我不确定,但我认为它是NAT-1 IP和很多计算机),并且我的服务器正在VPS上运行。 那么,如何从服务器回复客户端?

客户代码:

    void SendDataToServer(string Message)
    {
        IPAddress Ip = Dns.GetHostEntry("mydomain.com").AddressList[0];
        int Port = 1234;
        IPEndPoint Server = new IPEndPoint(Ip, Port);

        byte[] MessageInBytes = Encoding.UTF8.GetBytes(Message);
        MySocket.SendTo(MessageInBytes, Server);
    }

    void ReceiveDataFromServer(int Port) // this is running in background
    {
        UdpClient Client = new UdpClient(Port);
        IPEndPoint Server = new IPEndPoint(IPAddress.Any, Port);
        try
        {
            while (true)
            {
                byte[] MessageInBytes = Client.Receive(ref Server);
                string Message = Encoding.UTF8.GetString(MessageInBytes, 0, MessageInBytes.Length);
                MessageBox.Show(Message);
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(e);
        }
    }

服务器代码:

    static void StartReceiveing(int Port) // this is running in background
    {
        UdpClient Server = new UdpClient(Port);
        IPEndPoint Client = new IPEndPoint(IPAddress.Any, Port);

        try
        {
            while (true)
            {
                byte[] MessageInBytes = Server.Receive(ref Client);
                string Message = Encoding.UTF8.GetString(MessageInBytes, 0, MessageInBytes.Length);
                Console.WriteLine("Received message: " + Message);
                Task.Run(() => ReplyToClient("some text", Client));
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    static void ReplyToClient(string Message, IPEndPoint Client)
    {
        try
        {
            byte[] MessageInBytes = Encoding.UTF8.GetBytes(Message);
            NetClient.SendTo(MessageInBytes, Client);

            Console.WriteLine("Sending reply: " + Message);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }

0 个答案:

没有答案