Can I set the timeout for UdpClient in C#?

前端 未结 5 872
不知归路
不知归路 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:12

    Actually, it appears that UdpClient is broken when it comes to timeouts. I tried to write a server with a thread containing only a Receive which got the data and added it to a queue. I've done this sort of things for years with TCP. The expectation is that the loop blocks at the receive until a message comes in from a requester. However, despite setting the timeout to infinity:

    _server.Client.ReceiveTimeout = 0; //block waiting for connections
    _server.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
    

    the socket times out after about 3 minutes.

    The only workaround I found was to catch the timeout exception and continue the loop. This hides the Microsoft bug but fails to answer the fundamental question of why this is happening.

提交回复
热议问题