0

I am using the websocket-client and wanted to know how can I use ping/pong to check the connection is still open ?

I am using the short lived connection option but still want to check if the websocket has not disconnected in the meantime. Is it as simple as ws.ping() ? Will there be an exception of the sort?

import socket
from websocket import create_connection
ws = create_connection("ws://localhost/", # Dummy URL
                        socket = my_socket,
                        sockopt=((socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),))```
rustyocean
  • 233
  • 5
  • 14
  • call ws.recv() method and then check the attribute ws.connected – spramuditha Oct 22 '22 at 01:57
  • It takes a long time for that exception to be raised on recv https://github.com/websocket-client/websocket-client/blob/285e0a832e3212ef9ffa8c94fe26a30829353b32/websocket/_core.py#L527 – rustyocean Oct 22 '22 at 02:04
  • Try setting a timeout? Does this help? https://stackoverflow.com/questions/2719017/how-to-set-timeout-on-pythons-socket-recv-method – spramuditha Oct 22 '22 at 02:10
  • it is set to 5 seconds, but the exception shows up almost 18 seconds later – rustyocean Oct 22 '22 at 02:11
  • On second thoughts 18 secs isn't bad. There's a lag for sending the ping. But I'll check a little bit more. However I believe recv is the best option. – spramuditha Oct 22 '22 at 02:15

0 Answers0