且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

DatagramSocket类不能从UdpClient接收数据

更新时间:2023-11-19 17:39:10

我不熟悉的新DatagramSocket类,但通常绑定到127.0.0.1意味着你将只能接收发送到环回适配器的消息。由于你的包从另一台主机来了,就应该在NIC,而不是环回适配器来接收

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.

修改:从看为你使用,你可以使用 BindServiceNameAsync()方法,而不是 DatagramSocket的API文档BindEndpointAsync()以绑定到所有适配器指定的端口,这是相同的行为,我的System.Net.Sockets API下面的例子。所以,在你的榜样,你必须:

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");



当然,你还需要确保在桌面主机上的防火墙设置允许它。监听指定端口上的传入UDP数据包

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.

试试下面的代码:

    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.
        }
    }

请注意,在上面的代码,很显然你应该使用无论编码你发送跨的字符串。当我写的测试程序,我派在ASCII字符串。如果你在Unicode的发送,只需要使用 UnicodeEncoding.Unicode 而不是 ASCIIEncoding.ASCII

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.

如果没有这工作,你可能想摆脱像Wireshark的数据包捕获工具,以确保从RT主机的UDP包,其实,让桌面主机

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.