jam134 commited on
Commit
44eff57
Β·
verified Β·
1 Parent(s): 1f52f94

Update keep_alive.py

Browse files
Files changed (1) hide show
  1. keep_alive.py +20 -38
keep_alive.py CHANGED
@@ -1,44 +1,26 @@
1
- import websocket
2
  import time
 
3
 
4
- def on_message(ws, message):
5
- print(f"ζŽ₯ζ”Άεˆ°θ¨Šζ―: {message}")
6
-
7
- def on_error(ws, error):
8
- print(f"錯θͺ€: {error}")
9
 
10
- def on_close(ws, status_code, reason):
11
- print(f"ι€£ζŽ₯ε·²ι—œι–‰οΌŒη‹€ζ…‹η’Ό: {status_code}, εŽŸε› : {reason}")
12
 
13
- def on_open(ws):
14
- print("ι€£ζŽ₯ζˆεŠŸοΌŒδΏζŒι€£η·š...")
15
 
16
- def keep_alive_websocket(url, connect_duration=300, wait_duration=300):
17
- while True:
18
- try:
19
- ws = websocket.WebSocketApp(url,
20
- on_message=on_message,
21
- on_error=on_error,
22
- on_close=on_close)
23
- ws.on_open = on_open
24
-
25
- # η΄€ιŒ„ι–‹ε§‹ζ™‚ι–“
26
- start_time = time.time()
27
- ws.run_forever() # ι–‹ε§‹δΏζŒι€£ζŽ₯
28
-
29
- # η›£ζŽ§ι€£ζŽ₯ζŒηΊŒζ™‚ι–“
30
- while time.time() - start_time < connect_duration:
31
- time.sleep(1) # η­‰εΎ…δΈ€η§’ι˜
32
-
33
- ws.close() # εˆ‡ζ–·ι€£ζŽ₯
34
- print(f"ζŒηΊŒι€£ζŽ₯ {connect_duration} η§’εΎŒεˆ‡ζ–·γ€‚")
35
- time.sleep(wait_duration) # η­‰εΎ… 5 εˆ†ι˜ε†ι‡ζ–°ι€£ζŽ₯
36
-
37
- except Exception as e:
38
- print(f"WebSocket η™Όη”ŸιŒ―θͺ€: {e}")
39
- time.sleep(500) # ι€£ζŽ₯ε€±ζ•—εΎŒι‡θ©¦
40
 
41
- # 瀺例用法
42
- if __name__ == "__main__":
43
- url = "wss://huggingface.co/spaces/jam134/test" # ζ›Ώζ›η‚Ίδ½ ηš„ WebSocket URL
44
- keep_alive_websocket(url)
 
 
 
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")
9
 
10
+ def on_message(ws, message):
11
+ print(f"Message received: {message}")
12
 
13
+ def connect_websocket():
14
+ ws = websocket.WebSocketApp(
15
+ "wss://your-websocket-url",
16
+ on_open=on_open,
17
+ on_close=on_close,
18
+ on_message=on_message,
19
+ )
20
+ ws.run_forever()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
+ while True:
23
+ connect_websocket()
24
+ time.sleep(5 * 60) # η­‰εΎ… 5 εˆ†ι˜
25
+ websocket.WebSocketApp.close() # ι—œι–‰ι€£ζŽ₯
26
+ time.sleep(5 * 60) # η­‰εΎ… 5 εˆ†ι˜ε†ι‡ζ–°ι€£ζŽ₯