DatagramSocket cannot receive data from UdpClient

时光总嘲笑我的痴心妄想 提交于 2019-12-04 15:21:52

I'm not familiar with the new DatagramSocket class, but usually binding to 127.0.0.1 means that you will only receive messages sent to the loopback adapter. Since your packets are coming from another host, they should be received on a NIC, not the loopback adapter.

Edit: From looking at the documentation for the DatagramSocket API that you're using, you can just use the BindServiceNameAsync() method instead of BindEndpointAsync() in order to bind to the specified port on all adapters, which is the same behavior as my System.Net.Sockets API example below. So, in your example, you'd have:

g.BindServiceNameAsync("6700");

Of course, you'll also want to make sure your firewall settings on the desktop host allow it to listen for incoming UDP packets on the specified port.

Try the following code:

    using System.Net;
    using System.Net.Sockets;

    public class UdpState
    {
        public UdpClient client;
        public IPEndPoint ep;
    }

    ...

    private void btnStartListener_Click(object sender, EventArgs e)
    {
        UdpState state = new UdpState();
        //This specifies that the UdpClient should listen on EVERY adapter
        //on the specified port, not just on one adapter.
        state.ep = new IPEndPoint(IPAddress.Any, 31337);
        //This will call bind() using the above IP endpoint information. 
        state.client = new UdpClient(state.ep);
        //This starts waiting for an incoming datagram and returns immediately.
        state.client.BeginReceive(new AsyncCallback(bytesReceived), state);
    }

    private void bytesReceived(IAsyncResult async)
    {
        UdpState state = async.AsyncState as UdpState;
        if (state != null)
        {
            IPEndPoint ep = state.ep;
            string msg = ASCIIEncoding.ASCII.GetString(state.client.EndReceive(async, ref ep));
            //either close the client or call BeginReceive to wait for next datagram here.
        }
    }

Note that in the above code, you should obviously use whatever encoding you're sending the string across with. When I wrote that test app, I sent the string in ASCII. If you're sending it in Unicode, just use UnicodeEncoding.Unicode instead of ASCIIEncoding.ASCII.

If none of this works, you might want to break out a packet capture utility like Wireshark to make sure that the UDP packet from the RT host is, in fact, getting to the desktop host.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!