Python Sockets - Keeping a connection to a server alive from the client
<p>I'm currently working with python's socket library for the first time and i'm not very experienced with computer networking.</p>

<p>I'm able to connect to the server and the tcp handshake has happened as viewed by wireshark. After establishing a connection to the server(I have no control over the server), the connection stays open for a while, but after a small amount of time, the server sends a "FIN, ACK" and the connection is terminated. I'm trying to understand how I can keep this connection alive while the client is capable of reaching the server.</p>

<p>Looking at a tcp connection, it seems a packet can be sent every so often. Maybe a sort of keep alive message. I had thought using <code>socket.send('hello')</code> every 5 seconds in another thread would keep the connection with the server open, but I still get the "FIN, ACK" after some time.</p>

<p>In the documentation I found a <code>setsockopt()</code> but using this made no noticeable difference. I've tried <code>client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)</code> both before and after the connection is made. I don't completely understand how this method is supposed to work, so maybe I used it incorrectly. There isn't much mention of this. I read somewhere about it being broken on windows. I don't know the truth in that.</p>

<p>What am I missing? The documentation for sockets doesn't seem to have anything about this unless I may have missed something.</p>

<pre><code>import socket
import time
import threading

SERVER_IP = 'THE SERVER'
SERVER_PORT = SERVER_PORT

SOURCE_IP = socket.gethostname()
SOURCE_PORT = 57004

KEEP_ALIVE_INTERVAL = 5

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

def keep_alive(interval):
    data = 'hello'
    while True:
        client.send(data)
        time.sleep(interval)

client.connect((SERVER_IP, SERVER_PORT))

t = threading.Thread(target=keep_alive, args = (KEEP_ALIVE_INTERVAL,))
t.start()

while True:
    data = client.recv(1024)
    if not data:
        break
    print data
client.close()
</code></pre>