Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ping websocket server, so it doesn't disconnect me for being idle

I'm using websocket-client to connect to a websocket server. The server i'm connected to seems to be expecting me to ping it periodically or else it disconnects me.

Right when I connect to the server, it sends me this message:

0{"sid":"SomeID","upgrades":[],"pingInterval":25000,"pingTimeout":60000}

This seems to tell me the ping interval and ping timeout. I noticed that my websocket client is getting disconnected consistently ~1 minute and 25 seconds after I connect. And if you add up those numbers 60s + 25s you get 1 min and 25 seconds. So It seems I need to ping this server every so often so it doesn't disconnect me.

How do I ping the server? I tried ws.ping() but that didn't seem to exist. Do I need to send data to the server in some format it's expecting? Or is there some built in ping command?

    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("wss://socket.serverssite.com/socket.io/?transport=websocket",
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.run_forever()

Note: I made a websocket client in node (not python) and it doesn't get closed after 1 min 25 seconds. So It seems that has some built in ping that this python websocket client does not...

------------------------Edit-------------------------

Tried setting ping_interval and ping_timeout, but it's still closing:

2017-11-06 12:49:14.340037--------------------- Doing stuff

2017-11-06 12:49:14.340309--------------------- Doing stuff

send: '\x89\x80\\xd9\xc4\xdd'

2017-11-06 12:49:19.341680--------------------- Doing stuff

2017-11-06 12:49:19.341958--------------------- Doing stuff

send: '\x89\x80\xd9\x06\xef\xa8'

2017-11-06 12:49:24.343426--------------------- Doing stuff

2017-11-06 12:49:24.343769--------------------- Doing stuff

send: "\x89\x80\xe6\x92'\xb8"

send: '\x88\x823\xfb$\xd10\x13'

closed (Here is where the closed method gets called, the server shut me down)

like image 605
LampShade Avatar asked Nov 05 '17 07:11

LampShade


1 Answers

From the source code -

def run_forever(self, sockopt=None, sslopt=None,
                ping_interval=0, ping_timeout=None,
                http_proxy_host=None, http_proxy_port=None,
                http_no_proxy=None, http_proxy_auth=None,
                skip_utf8_validation=False,
                host=None, origin=None)

Specifying the ping_interval should work for you.

ws.run_forever(ping_interval=70, ping_timeout=10)
like image 194
Jay Avatar answered Sep 17 '22 22:09

Jay