Search code examples
c#socketsclientlistenerwait

C# (socket) wait for connection during x seconds


I'm making a client socket. This socket will send some data to another socket and wait for its response (if any). I want my client socket to wait for a response for 5 seconds. The problem is, if I put it in Receiver mode, the program will only run after it gets a connection. I want my program to be listening for a duration of time, not until he gets a response (witch could be never, if the other socket isn't programmed to answer).


Solution

  • The Socket class contains a ReceiveTimeout property, which by default is Infinite.

    https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.receivetimeout(v=vs.110).aspx

    If you set this value, then the Socket.Recieve() method will only block until the timeout has passed, then will throw a TimeoutException.

    Socket sock;
    
    //socket connection and sending data
    sock.ReceiveTimeout = 5000;
    try {
        data = sock.Receive();
    }
    catch (TimeoutException ex)
    {
        // it never answered
    }