添加掉线重连

This commit is contained in:
John Smith 2018-05-14 01:02:53 +08:00
parent 203f503ecc
commit 600038b683

View File

@ -8,6 +8,7 @@ from enum import IntEnum
import requests import requests
import websockets import websockets
from websockets.exceptions import ConnectionClosed
class Operation(IntEnum): class Operation(IntEnum):
@ -47,6 +48,8 @@ class BLiveClient:
else: else:
self._room_id = res.json()['data']['room_id'] self._room_id = res.json()['data']['room_id']
if self._future is not None:
return
self._future = gather( self._future = gather(
self._message_loop(), self._message_loop(),
self._heartbeat_loop() self._heartbeat_loop()
@ -71,6 +74,7 @@ class BLiveClient:
return header + body return header + body
async def _message_loop(self): async def _message_loop(self):
while True:
try: try:
# 连接 # 连接
async with websockets.connect(self.WEBSOCKET_URL) as websocket: async with websockets.connect(self.WEBSOCKET_URL) as websocket:
@ -80,8 +84,15 @@ class BLiveClient:
# 处理消息 # 处理消息
async for message in websocket: async for message in websocket:
await self._handle_message(message) await self._handle_message(message)
except CancelledError: except CancelledError:
pass break
except ConnectionClosed:
self._websocket = None
# 重连
print('掉线重连中')
await sleep(5)
continue
finally: finally:
self._websocket = None self._websocket = None
@ -96,15 +107,19 @@ class BLiveClient:
await self._websocket.send(self._make_packet(auth_params, Operation.AUTH)) await self._websocket.send(self._make_packet(auth_params, Operation.AUTH))
async def _heartbeat_loop(self): async def _heartbeat_loop(self):
try:
while True: while True:
try:
if self._websocket is None: if self._websocket is None:
await sleep(0.5) await sleep(0.5)
else: else:
await self._websocket.send(self._make_packet({}, Operation.SEND_HEARTBEAT)) await self._websocket.send(self._make_packet({}, Operation.SEND_HEARTBEAT))
await sleep(30) await sleep(30)
except CancelledError: except CancelledError:
pass break
except ConnectionClosed:
# 等待重连
continue
async def _handle_message(self, message): async def _handle_message(self, message):
offset = 0 offset = 0
@ -125,8 +140,12 @@ class BLiveClient:
body = json.loads(body.decode('utf-8')) body = json.loads(body.decode('utf-8'))
await self._handle_command(body) await self._handle_command(body)
# elif header.operation == Operation.RECV_HEARTBEAT: elif header.operation == Operation.RECV_HEARTBEAT:
# pass pass
else:
body = message[offset + self.HEADER_STRUCT.size: offset + header.total_len]
print('未知包类型:', header, body)
offset += header.total_len offset += header.total_len
@ -148,6 +167,9 @@ class BLiveClient:
elif cmd == 'WELCOME': # 欢迎 elif cmd == 'WELCOME': # 欢迎
pass pass
elif cmd == 'WELCOME_GUARD': # 欢迎房管
pass
elif cmd == 'SYS_MSG': # 系统消息 elif cmd == 'SYS_MSG': # 系统消息
pass pass