Can I set the timeout for UdpClient in C#?

前端 未结 5 871
不知归路
不知归路 2020-12-09 08:05

I am wondering whether I can set a timeout value for UdpClient receive method.

I want to use block mode, but because sometimes udp will lost packet, my program udpCl

5条回答
  •  天命终不由人
    2020-12-09 08:22

    What Filip is referring to is nested within the socket that UdpClient contains (UdpClient.Client.ReceiveTimeout).

    You can also use the async methods to do this, but manually block execution:

    var timeToWait = TimeSpan.FromSeconds(10);
    
    var udpClient = new UdpClient( portNumber );
    var asyncResult = udpClient.BeginReceive( null, null );
    asyncResult.AsyncWaitHandle.WaitOne( timeToWait );
    if (asyncResult.IsCompleted)
    {
        try
        {
            IPEndPoint remoteEP = null;
            byte[] receivedData = udpClient.EndReceive( asyncResult, ref remoteEP );
            // EndReceive worked and we have received data and remote endpoint
        }
        catch (Exception ex)
        {
            // EndReceive failed and we ended up here
        }
    } 
    else
    {
        // The operation wasn't completed before the timeout and we're off the hook
    }
    

提交回复
热议问题