Update keep_alive.py
Browse files- 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 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
| 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秒再重試
|