使用udpClient连续接收消息

本文关键字:消息 连续 udpClient 使用 | 更新日期: 2023-09-27 18:07:08

我正在寻找通过C#中的UdpClient类接收和处理消息的最佳解决方案。有人能解决这个问题吗?

使用udpClient连续接收消息

试试下面的代码:

//Client uses as receive udp client
UdpClient Client = new UdpClient(Port);
try
{
     Client.BeginReceive(new AsyncCallback(recv), null);
}
catch(Exception e)
{
     MessageBox.Show(e.ToString());
}
//CallBack
private void recv(IAsyncResult res)
{
    IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 8000);
    byte[] received = Client.EndReceive(res, ref RemoteIpEndPoint);
    //Process codes
    MessageBox.Show(Encoding.UTF8.GetString(received));
    Client.BeginReceive(new AsyncCallback(recv), null);
}

对于使用TAP代替Begin/End方法的新方法,您可以在。net 4.5

中使用以下方法

很简单!

异步方法
    private static void UDPListener()
    {
        Task.Run(async () =>
        {
            using (var udpClient = new UdpClient(11000))
            {
                string loggingEvent = "";
                while (true)
                {
                    //IPEndPoint object will allow us to read datagrams sent from any source.
                    var receivedResults = await udpClient.ReceiveAsync();
                    loggingEvent += Encoding.ASCII.GetString(receivedResults.Buffer);
                }
            }
        });
    }

同步方法

与上面的asynchronous方法相反,这也可以在synchronous方法中以非常类似的方式实现:

    private static void UDPListener()
    {
        Task.Run(() =>
        {
            using (var udpClient = new UdpClient(11000))
            {
                string loggingEvent = "";
                while (true)
                {
                    //IPEndPoint object will allow us to read datagrams sent from any source.
                    var remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    var receivedResults = udpClient.Receive(ref remoteEndPoint);
                    loggingEvent += Encoding.ASCII.GetString(receivedResults);
                }
            }
        });
    }