ref:
[1] https://www.codenong.com/12248132/

[2] https://vimsky.com/examples/detail/python-attribute-socket.SIO_KEEPALIVE_VALS.html

def set_keep_alive(after_idle_min=25, interval_min=1, max_fails=5):
        if sock is not None:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

            if hasattr(socket, "TCP_KEEPIDLE") and hasattr(socket, "TCP_KEEPINTVL") and hasattr(socket, "TCP_KEEPCNT"):
                sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, after_idle_min * 60)
                sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval_min * 60)
                sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, max_fails)
            elif hasattr(socket, "SIO_KEEPALIVE_VALS"):
                sock.ioctl(socket.SIO_KEEPALIVE_VALS, (1, after_idle_min * 60 * 1000, interval_min * 60 * 1000))

客户端或服务端,有一边设置即可