jam134 commited on
Commit
f9bf30f
·
verified ·
1 Parent(s): 0c674aa

Update keep_alive.py

Browse files
Files changed (1) hide show
  1. keep_alive.py +18 -10
keep_alive.py CHANGED
@@ -1,8 +1,14 @@
1
  import time
 
2
  import websocket
3
 
4
  def on_open(ws):
5
  print("Connection opened")
 
 
 
 
 
6
 
7
  def on_close(ws):
8
  print("Connection closed")
@@ -11,13 +17,15 @@ def on_message(ws, message):
11
  print(f"Message received: {message}")
12
 
13
  def keep_alive_websocket(url):
14
- ws = websocket.WebSocketApp(
15
- url,
16
- on_open=on_open,
17
- on_close=on_close,
18
- on_message=on_message,
19
- )
20
- ws.run_forever()
21
-
22
- if __name__ == "__main__":
23
- pass
 
 
 
1
  import time
2
+ import threading
3
  import websocket
4
 
5
  def on_open(ws):
6
  print("Connection opened")
7
+ def run(*args):
8
+ while True:
9
+ time.sleep(30) # 每30秒發送一次心跳
10
+ ws.send("ping") # 發送心跳消息
11
+ threading.Thread(target=run).start()
12
 
13
  def on_close(ws):
14
  print("Connection closed")
 
17
  print(f"Message received: {message}")
18
 
19
  def keep_alive_websocket(url):
20
+ while True:
21
+ try:
22
+ ws = websocket.WebSocketApp(
23
+ url,
24
+ on_open=on_open,
25
+ on_close=on_close,
26
+ on_message=on_message,
27
+ )
28
+ ws.run_forever()
29
+ except Exception as e:
30
+ print(f"Error: {e}. Reconnecting in 5 seconds...")
31
+ time.sleep(5) # 出錯後等待5秒再重試