Yeah, this will happen in WebSocket because we have to send the heartbeat (ping) or reconnect logic.
You need 2 things:
Heartbeat (to detect dead connection)
Auto-reconnect logic
Below is the sample code you can refer:
import time
import threading
last_tick_time = time.time()
RECONNECT_TIMEOUT = 5 # seconds
def on_tick(tick):
global last_tick_time
last_tick_time = time.time()
print("Tick:", tick)
def start_socket():
print("Starting WebSocket...")
# Actuall broket connect code
# ws.connect()
def stop_socket():
print("Stopping WebSocket...")
# Actual close
# ws.close()
def reconnect():
print("Reconnecting...")
stop_socket()
time.sleep(1)
start_socket()
def heartbeat_checker():
while True:
time.sleep(1)
if time.time() - last_tick_time > RECONNECT_TIMEOUT:
print("No ticks received. Connection seems dead.")
reconnect()
# Start everything
start_socket()
threading.Thread(target=heartbeat_checker, daemon=True).start()
# Simulated tick loop
while True:
time.sleep(2)
on_tick({"price": 100})
Since, websocket are not 100 percent reliabile we need the heartbit or reconnect logic.