Nick Tucker
Nick Tucker

Reputation: 347

ReceiveFromAsync Example

Does any one have an example for ReceiveFromAsync works with regard to UDP? i couldn't find any sample code. I can find a few TCP sample but msdn say 'The ReceiveFromAsync method is used primarily to receive data on a connectionless socket'.

Thanks, Nick

Upvotes: 3

Views: 5102

Answers (2)

Schulle0815
Schulle0815

Reputation: 61

If performance is not a concern, a quick and simple approach could be UdpClient's ReceiveAsync method:

https://msdn.microsoft.com/de-de/library/system.net.sockets.udpclient.receiveasync(v=vs.110).aspx

Then you can use the result (UdpReceiveResult) to filter for a specific remote endpoint where you want to receive data from. Here is a small example:

private async void ReceiveBytesAsync(IPEndPoint filter)
{
    UdpReceiveResult receivedBytes  = await this._udpClient.ReceiveAsync();

    if (filter != null)
    {
        if (receivedBytes.RemoteEndPoint.Address.Equals(filter.Address) &&
                (receivedBytes.RemoteEndPoint.Port.Equals(filter.Port)))
        {
            // process received data
        }
    }
}

Upvotes: 1

CalumMcCall
CalumMcCall

Reputation: 1687

Perhaps it might be easier to use UdpClient's async BeginReceive() method?

http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.beginreceive.aspx

Upvotes: 2

Related Questions