2 wlovexr1314 wlovexr1314 于 2017.09.18 00:22 提问

C# UDP通讯,外网客户端向内网服务器发送数据接受不到

内网发送接收消息没问题,外网路由器做了UDP映射,客户端发送数据,能在内网PC电脑上抓包出来,但是服务器接收不到这个消息
private void freeDNS_Server_Load(object sender, EventArgs e)
{
receiveClient = new UdpClient(port);
Thread myThread = new Thread(ReceiveData);
myThread.IsBackground = true;
myThread.Start();
}

    //在后台运行的接收线程   
    private void ReceiveData()
    {
        //在本机指定的端口接收  
        UdpState udpState = new UdpState();
        udpState.ipEndPoint = null;
        udpState.udpClient = receiveClient;
        //接收从远程主机发送过来的信息;  
        IAsyncResult ar = udpState.udpClient.BeginReceive(ReceiveUdpClientCallback, udpState);
        ar.AsyncWaitHandle.WaitOne();
        MessageBox.Show("线程结束");
    }


    //接收信息回调方法  
    void ReceiveUdpClientCallback(IAsyncResult ar)
    {
        try
        {
            UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).udpClient;
            IPEndPoint remote = (IPEndPoint)((UdpState)(ar.AsyncState)).ipEndPoint;
            Byte[] receiveBytes = u.EndReceive(ar, ref remote);
            string str = Encoding.UTF8.GetString(receiveBytes, 0, receiveBytes.Length);
            AddItem(listBox_freeDNS_Server, string.Format("来自{0}:{1}", remote, str));
            ReceiveData();//继续接受数据  
        }
        catch (Exception ex)
        {
            AddItem(listBox_freeDNS_Server, string.Format("错误信息{0}", ex.ToString()));
        }
    }

    delegate void AddListBoxItemCallback(string text);
    private void AddListBoxItem(string text)
    {
        //如果listBoxReceive被不同的线程访问则通过委托处理;  
        if (listBox_freeDNS_Server.InvokeRequired)
        {
            this.Invoke(listBoxCallback, text);
        }
        else
        {
            listBox_freeDNS_Server.Items.Add(text);
            listBox_freeDNS_Server.SelectedIndex = listBox_freeDNS_Server.Items.Count - 1;
            listBox_freeDNS_Server.ClearSelected();
        }
    }

2个回答

ouyangsixian
ouyangsixian   2017.09.18 09:43

一:检查防火墙是否关闭
二:外网客户端机器的UDP端口是否开通

wlovexr1314
wlovexr1314 防火墙关闭了,异步发送的数据,在服务器能抓包到外网发送过来的数据,但就是服务器接收不到
2 个月之前 回复
wlovexr1314
wlovexr1314   2017.09.19 15:27

防火墙关闭了,异步发送的数据,在服务器能抓包到外网发送过来的数据,但就是服务器接收不到

Csdn user default icon
上传中...
上传图片
插入图片