System.Net.Sockets.UdpClient.ReceiveAsync C# (CSharp) Method

ReceiveAsync() public method

public ReceiveAsync ( ) : Task
return Task
        public Task<UdpReceiveResult> ReceiveAsync()
        {
            return Task<UdpReceiveResult>.Factory.FromAsync(
                (callback, state) => ((UdpClient)state).BeginReceive(callback, state),
                asyncResult =>
                {
                    var client = (UdpClient)asyncResult.AsyncState;
                    IPEndPoint remoteEP = null;
                    byte[] buffer = client.EndReceive(asyncResult, ref remoteEP);
                    return new UdpReceiveResult(buffer, remoteEP);
                },
                state: this);
        }

Usage Example

        private static async Task ReaderAsync(int port, string groupAddress)
        {
            using (var client = new UdpClient(port))
            {
                if (groupAddress != null)
                {
                    client.JoinMulticastGroup(IPAddress.Parse(groupAddress));
                    WriteLine($"joining the multicast group {IPAddress.Parse(groupAddress)}");
                }

                bool completed = false;
                do
                {
                    WriteLine("starting the receiver");
                    UdpReceiveResult result = await client.ReceiveAsync();
                    byte[] datagram = result.Buffer;
                    string received = Encoding.UTF8.GetString(datagram);
                    WriteLine($"received {received}");
                    if (received == "bye")
                    {
                        completed = true;
                    }
                } while (!completed);
                WriteLine("receiver closing");

                if (groupAddress != null)
                {
                    client.DropMulticastGroup(IPAddress.Parse(groupAddress));
                }
            }
        }
All Usage Examples Of System.Net.Sockets.UdpClient::ReceiveAsync