Search code examples
c#socketsudpdatagram

UDP Sockets in C#?


If socket.ReceiveFrom (byte [] message, EndPoint endPoint) is used to receive data on a binded UDP socket, and no data is received what happens? Does it keep waiting for data to arrive or does it continue? I am specifically talking about UDP Datagrams.


Solution

  • If the goal is to force your socket to stop listening after X number of seconds so you can do something else (such as checking if the application is shutting down) and you are using synchronous sockets then I would recommend setting the Socket.ReceiveTimeout to X number of seconds (times 1000 since Socket.ReceiveTimeout is in milliseconds) and then catch the resulting exception that is raised on timeout.