發佈日期:

python的socket-io-client 4.5.1不會自動重連問題

問題版本

python-socketio 4.5.1
相關討論串: https://github.com/miguelgrinberg/python-socketio/issues/485
can not reconnect after 503 error

解決方法

自己寫重連的程式碼

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import socketio
from threading import Timer
 
timer = None
address = "http://127.0.0.1:2027"
sio = socketio.Client(reconnection=False, logger=False, engineio_logger=False)
isConnected = False
 
def connectSocket():
    global timer
    try:
        sio.connect(address, transports='polling')
    except:
        if timer is not None:
            timer.cancel()
        timer = Timer(1.0, connectSocket)
        timer.start()
 
def close():
    global sio
    global timer
    global isConnected
    sio.disconnect()
    isConnected = False
    if timer is not None:
        timer.cancel()
 
@sio.event
def test():
    print('(test)'
 
 
def send(data):
    sio.emit('send', data)
 
 
@sio.event
def connect():
    global isConnected
    print('(connect)')
 
 
@sio.event
def disconnect():
    global timer
    global isConnected
    print('(disconnected)')
    sio.disconnect()
    isConnected = False
    if timer is not None:
        timer.cancel()
    timer = Timer(1.0, connectSocket)
    timer.start()