Do TCP sockets automatically close after some time if no data is sent?

前端 未结 4 1860
一向
一向 2021-02-03 10:15

I have a client server situation where the client opens a TCP socket to the server, and sometimes long periods of time will pass with no data being sent between them. I have enc

相关标签:
4条回答
  • 2021-02-03 10:58

    On Windows, sockets with no data sent are a big source for trouble in many applications and must be handled correctly.

    The problem is, that SO_KEEPALIVE's period can be set system-wide (otherwise, a default is useless two hours) or with the later winsock API.

    Therefore, many applications do send some occasional byte of data every now and then (to be disregarded by the peer) only to make the network layer declare disconnection after ACK is not received (after all due retransmissions done by the layer and ack timeout).

    Answering your question: no, the sockets do not disconnect automatically.

    Yet, you must be careful with the above issue. What complicates it further is that testing this behavior is very hard. For example, if you set everything correctly and you expect to detect disconnection properly, you cannot test it by disconnecting the physical layer. This is because the NIC will sense the carrier loss and the socket layer will signal to close all application sockets that relied on it. A good way to test it is connect two computers with 3 legs and two switches in between, disconnecting the middle leg, thus preventing carrier loss but still physically disconnecting the machines.

    0 讨论(0)
  • 2021-02-03 10:58

    There is a timeout built in to TCP but you can adjust it, See SendTimeout and ReciveTimeout of the Socket class, but I have a suspiciouion that is not your problem. A NAT router may also have a expiration time for TCP connections before it removes it from it's port forwarding table. If no traffic passes within the time of that timeout on the router it will block all incoming traffic (as it cleared the forwarding information from it's memory so it does not know what computer to send the traffic to), also the outgoing connection will likely have a different source port so the server may not recognize it as the same connection.

    0 讨论(0)
  • 2021-02-03 11:01

    It's more secure to use Keep-alive option (SO_KEEPALIVE under linux), to prevent disconnect due to inactivity, but this may generate some extra packets.

    This sample code do it under linux:

    int val = 1;
    ....
    // After creating the socket
    if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (char *)&val, sizeof(val)))                   
        fprintf(stderr, "setsockopt failure : %d", errno);
    

    Regards.

    0 讨论(0)
  • 2021-02-03 11:11

    TCP sockets don't automatically close at all. However TCP connections do. But if this is happening between peers in the same computer the connection should never be dropped as long as both peers exist and have their sockets open.

    0 讨论(0)
提交回复
热议问题