Search code examples
c#socketstcpclientsocketexceptionnetworkstream

How to Increase the connection timeout threshold in Socket/TcpClient C#?


I have the connection from client to server using Socket/TcpClient. After I started it, the connection established between client and server, they can sent/recieved data between client and server. The server send data to client, and client will reply. This is working well during 13minutes. But after 13minutes, I get this error Connection timed out. A connection attempt failed because the connected party did not properly respond after a period of time, or the established connection failed because the connected host has failed to respond. . I go around and see this code WSAETIMEDOUT 10060. It's related to connection timeout. So, I don't know I can increase the connection timeout threshold, this way will increase the connection between client to server more than 13minutes probably. I try set some option like this, but I'm not sure what's the correct option.

    /*using Socket*/
    var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);           
    client.Connect(IPAddress.Parse("10.10.10.120"), 5000);
    
    /*using TcpClient*/
    var client1 = new TcpClient();  
    client1.Connect(IPAddress.Parse("10.10.10.120"), 5000);
                
    ////which option should be choose in this case
    //client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);          
    //client.NoDelay = true; 
    //client.SendTimeout = 180000; 
    //client.ReceiveTimeout = 180000;  
    //client.LingerState = new LingerOption(true, 180);
    //client.Ttl = 42;
    //client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);
    //client.Poll(180000000, SelectMode.SelectRead);
    //client.Poll(180000000, SelectMode.SelectWrite);

Solution

  • By the way, I found resolve by myself, just spend more time to debug and see what's exactly data transfer. Besides, I use this code working well until now. So, if anyone get same issue, can try do like that.

      /*using Socket*/
        var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  
        client.ReceiveTimeout=180000;
        client.SendTimeout=180000;
        client.Connect(IPAddress.Parse("10.10.10.120"), 5000);
        
        /*using TcpClient*/
        var client1 = new TcpClient();  
        client1.Client.ReceiveTimeout=180000;
        client1.Client.SendTimeout=180000;
        client1.Connect(IPAddress.Parse("10.10.10.120"), 5000);