DatagramSocket 套接字停止接收数据包

DatagramSocket socket stop receiving packet

我用 DatagramSocket 写了一个测试程序来接收数据。但是在收到 5 或 6 个数据包后,这不是收到更多的数据包!

有人对此有解决方案吗?

我的测试代码是:

public MainPage()
{
    this.InitializeComponent();
}

private void Page_Loaded(object sender, RoutedEventArgs e)
        {

            Listen();
        }
private async void Listen()
    {
        try
        {
            Windows.Networking.Sockets.DatagramSocket socket = new Windows.Networking.Sockets.DatagramSocket();

            socket.MessageReceived += Socket_MessageReceived;

            //You can use any port that is not currently in use already on the machine.
            string serverPort = "1337";

            //Bind the socket to the serverPort so that we can start listening for UDP messages from the UDP echo client.
            await socket.BindServiceNameAsync(serverPort);
        }
        catch (Exception e)
        {
            //Handle exception.
        }
    }

    public async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args)
    {
        //Read the message that was received from the UDP echo client.
        Stream streamIn = args.GetDataStream().AsStreamForRead();
        StreamReader reader = new StreamReader(streamIn);

        string message = await reader.ReadLineAsync();


        await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
            () =>
            {
                Alpha.Text = message;


            }
            );
        }

我已使用 wireshark 进行跟踪以检查我是否正在接收数据,它收到了,但在我的 visual studio 解决方案中它不起作用。

我用过Control.InboundBufferSizeInBytes然后它就可以正常工作了!

        listener = new DatagramSocket();
        listener.MessageReceived += MessageReceived;
        listener.Control.InboundBufferSizeInBytes = 1;

        await listener.BindServiceNameAsync("1337");

这是因为你刚好打开了你的UDP Listener的另一个实例,或者你Initialize在错误的地方!