user6897207
user6897207

Reputation:

Setting ReceiveTimeout in Socket when receiving data

I have a Client using Socket with the below code for Receiving Data.

/** Some Code Above **/
private static ManualResetEvent receiveDone = new ManualResetEvent(false);
byte[] receivedBytes = new byte[65535];
String msg = null;

public String ReceiveMessage() {
    csocket.BeginReceive(receivedBytes, 0, receivedBytes.Length, SocketFlags.None, new AsyncCallback(receiveCallback), csocket);
    receiveDone.WaitOne();
    return msg;
}

private void receiveCallback(IAsyncResult ar){
    try{
        Socket socket = (Socket)ar.AsyncState;
        socket.ReceiveTimeout = 10000;  /**** Not  Working ****/
        int received = socket.EndReceive(ar);
        byte[] dataBuf = new byte[received];
        Array.Copy(receivedBytes, dataBuf, received);
        msg = (Encoding.ASCII.GetString(dataBuf)); 
        Console.WriteLine("Message Received: " + msg);
        receiveDone.Set();
    }catch (SocketException e){
        if (e.SocketErrorCode == SocketError.TimedOut){
            Console.WriteLine("SocketExecption => Timeout");
        }else{
            Console.WriteLine("SocketExecption => " + e.ToString());
        }
    }catch (Exception e){
        Console.WriteLine("Execption => " + e.ToString());
    }
}

The Data is Receiving however I've set ReceiveTimeout to 10000 but it's not working. Did I put ReceiveTimeout in the wrong line? If so then where should I initialize the ReceiveTimeout?

I found the below code where ReceiveTimeout is Set and working but I prefer to use BeginReceive() method.

try{
    byte[] byt = new byte[65535];
    socket.ReceiveTimeout = 10000;
    socket.Receive(byt);
    Console.WriteLine("Message: " + Encoding.UTF8.GetString(byt));
}catch (SocketException e){
    if (e.SocketErrorCode == SocketError.TimedOut)
    {
        Console.WriteLine("TimeOut");
    }else{
        Console.WriteLine("Unknown SocketExecption: " + e.ToString());
    }
}catch (Exception e){
    Console.WriteLine("Unknown Exception:" + e.ToString());
}

This makes me confused when setting ReceiveTimeout.

Upvotes: 2

Views: 3998

Answers (1)

Tadija Bagarić
Tadija Bagarić

Reputation: 2701

Possible duplicate: How to handle timeout in Async Socket?

ReceiveTimeout doesn't work for Asynchronous calls. Proposed solution is to use own timer.

From msdn for Socket.ReceiveTimeout:

This option applies to synchronous Receive calls only. If the time-out period is exceeded, the Receive method will throw a SocketException.

Upvotes: 1

Related Questions