我使用python-socketio构建了一个socket.io客户端:
import socketio
NAMESPACE = '/bballMsg'
URL = 'ws://x.x.x.x:3080?cid=1000000&puid=50000&nickName=PressureTest'
class MyCustomNamespace(socketio.ClientNamespace):
def on_connect(self):
print(f'{self.client.sid} is connected')
def on_connect_error(self):
print(f'{self.client.sid} is error')
def on_disconnect(self):
print(f'{self.client.sid} is disconnected')
def on_LIVE_DANMAKU_640014_438089(self, data):
print(data)
if __name__ == '__main__':
sio = socketio.Client(logger=True, engineio_logger=True)
sio.register_namespace(MyCustomNamespace(NAMESPACE))
sio.connect(URL, namespaces=[NAMESPACE])
sio.emit('subscribe', data={'channel': 'LIVE_DANMAKU_640014_438089'}, namespace=NAMESPACE)
sio.wait()
但是我发现有两个连接,并且几秒钟后一个已从ESTABLISHED更改为CLOSE_WAIT,然后再也不会释放
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
python3.7 70194 xxx 5u IPv4 0x366e9ef075952b47 0t0 TCP y.y.y.y:54183->x.x.x.x:stm_pproc (CLOSE_WAIT)
python3.7 70194 xxx 6u IPv4 0x366e9ef08c7beb47 0t0 TCP y.y.y.y:54184->x.x.x.x:stm_pproc (ESTABLISHED)
然后我将代码重写为以下内容
import asyncio
import socketio
NAMESPACE = '/bballMsg'
URL = 'ws://x.x.x.x:3080?cid=1000000&puid=50000&nickName=PressureTest'
class MyCustomNamespace(socketio.AsyncClientNamespace):
def on_connect(self):
print(f'{self.client.sid} is connected')
def on_connect_error(self):
print(f'{self.client.sid} is error')
def on_disconnect(self):
print(f'{self.client.sid} is disconnected')
def on_LIVE_DANMAKU_640014_438089(self, data):
print(data)
loop = asyncio.get_event_loop()
sio = socketio.AsyncClient(logger=True, engineio_logger=True)
sio.register_namespace(MyCustomNamespace(NAMESPACE))
async def start_server():
await sio.connect(URL, namespaces=[NAMESPACE])
await sio.emit('subscribe', data={'channel': 'LIVE_DANMAKU_640014_438089'}, namespace=NAMESPACE)
await sio.wait()
if __name__ == '__main__':
loop.run_until_complete(start_server())
我发现只有一个连接,但是发生了新问题,大多数时间在'emit'之后都没有收到回调