Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Sockets - Keeping a connection to a server alive from the client

I'm currently working with python's socket library for the first time and i'm not very experienced with computer networking.

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.

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 socket.send('hello') every 5 seconds in another thread would keep the connection with the server open, but I still get the "FIN, ACK" after some time.

In the documentation I found a setsockopt() but using this made no noticeable difference. I've tried client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) 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.

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

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()
like image 452
God Usopp Avatar asked Oct 29 '22 22:10

God Usopp


1 Answers

For enabling keep alive there is a duplicate question at How to change tcp keepalive timer using python script?

Keep in mind some servers and intermediate proxies forcibly close long lived connections regardless of keep alives being used or not, in which case you will see a FIN,ACK after X amount of time no matter what.

like image 91
danny Avatar answered Nov 15 '22 05:11

danny