0

我正在使用以下代码从 udp 套接字读取数据,该代码运行良好。现在我需要将'received'从recv传回调用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);

        }
    }
4

1 回答 1

1

在 .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);
    }
}
于 2013-07-11T11:48:05.670 回答