Beginreceive/Endreceive传递参数

本文关键字:参数 Endreceive Beginreceive | 更新日期: 2023-09-27 18:21:53

我正在使用以下代码从udp套接字中读取,该代码运行良好。现在我需要将recv的"received"返回到主叫main。这是怎么做到的。

   try
        {
          client.BeginReceive(new AsyncCallback(recv), client);
        }

   private static void recv(IAsyncResult res)
    {
        try
        {
            UdpClient c = (UdpClient)(res.AsyncState);
            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 162);           
            byte[]  received = c.EndReceive(res, ref RemoteIpEndPoint);
            Console.WriteLine(ASCIIEncoding.ASCII.GetString(received));
            c.BeginReceive(new AsyncCallback(recv), c);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }

Beginreceive/Endreceive传递参数

在.Net 4.5中,您可以像这样使用async/await

using (var udpClient = new UdpClient())
{
    try
    {
        udpClient.Connect(IPAddress.Any, 162);
        UdpReceiveResult receiveAsync = await udpClient.ReceiveAsync();
        Console.WriteLine(Encoding.ASCII.GetString(receiveAsync.Buffer));
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
}