C#Framework中的UDP数据报套接字(来自UWP的端口)

时间:2017-11-08 18:07:50

标签: c# .net datagram

我正在尝试将以下代码从UWP移植到C#framework(WPF app)

public class DatagramSocket : IDatagramSocket
{
    private Windows.Networking.Sockets.DatagramSocket socket;

    public DatagramSocket()
    {
        socket = new Windows.Networking.Sockets.DatagramSocket();
        socket.MessageReceived += Socket_MessageReceived;
    }

    public event Action<DatagramSocketMessage> MessageReceived;

    public async Task Bind(string profile, int liveViewPort)
    {
        Debug.WriteLine($"Binding to {profile} on port {liveViewPort}");
        await socket.BindEndpointAsync(new HostName(profile), liveViewPort.ToString());
    }

    public void Dispose()
    {
        socket.Dispose();
    }

    private void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
    {
        using (var reader = args.GetDataReader())
        {
            var buf = new byte[reader.UnconsumedBufferLength];
            reader.ReadBytes(buf);
            MessageReceived?.Invoke(new DatagramSocketMessage(args.RemoteAddress.CanonicalName, buf));
        }
    }
}

我尝试了以下内容,但永远不会调用OnUdpData回调:

public class DatagramSocket : IDatagramSocket
{
    public UdpClient socket;
    public IPEndPoint ep;

    public event Action<DatagramSocketMessage> MessageReceived;

    public async Task Bind(string profile, int liveViewPort)
    {
        socket = new UdpClient(profile, liveViewPort);
        socket.BeginReceive(OnUdpData, socket);
    }

    void OnUdpData(IAsyncResult result)
    {
        if (_isDisposed)
            return;

        var socket = result.AsyncState as UdpClient;

        // points towards whoever had sent the message:
        IPEndPoint source = new IPEndPoint(0, 0);
        // get the actual message and fill out the source:
        byte[] message = socket.EndReceive(result, ref source);

        MessageReceived?.Invoke(new DatagramSocketMessage(socket.ToString(), message));
        socket.BeginReceive(OnUdpData, socket);
    }

    private volatile bool _isDisposed;
    public void Dispose()
    {
        _isDisposed = true;
        socket.Dispose();
    }
}

还尝试了一种无法解决的异步解决方案。

    public async Task Bind(string profile, int liveViewPort)
    {
        Task.Run(async () =>
        {
            using (var udpClient = new UdpClient(profile, liveViewPort))
            {
                while (!_isDisposed)
                {
                    var receivedResults = await udpClient.ReceiveAsync();
                    MessageReceived?.Invoke(new DatagramSocketMessage(udpClient.ToString(), receivedResults.Buffer));

                }
            }
        });
    }

有什么建议吗?谢谢

1 个答案:

答案 0 :(得分:0)

找到原因,这是windows防火墙阻止访问。