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

前端 未结 4 1849
一向
一向 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 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.

提交回复
热议问题