我有多个使用websocket的任务。我想检测websocket的连接关闭,然后重新连接websocket,我通过一个名为break_task的变量做它,如果它是真的那么在任务中有一个连接关闭检测,在代码下面和我得到的错误异常(我使用python 3.6):
break_task = False
async def value_1():
global break_task
msg_dict = deepcopy(MESG)
async with websockets.connect('wss://api.xxxxx') as ws:
await ws.send(json.dumps(msg_dict))
while break_task == False:
try:
res = await ws.recv()
except ConnectionClosed:
print('CONNECTION CLOSED raised exception in value_1() -> TRYING TO RECONNECT !!!')
break_task = True
break
async def value_2():
global break_task
auth_dict = deepcopy(PAYLOAD)
async with websockets.connect('wss://api.xxxxx') as ws:
await ws.send(json.dumps(auth_dict))
while break_task == False:
await asyncio.sleep(0.05)
try:
res = await ws.recv()
except ConnectionClosed:
print('CONNECTION CLOSED raised exception in value_2() -> TRYING TO RECONNECT !!!')
break_task = True
break
data = json.loads(res)
和...
while True:
if (break_task == False):
tasks = value_1(), value_2()
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(*tasks))
elif (break_task == True):
tasks = None
loop.stop()
loop.close()
break_task = False
我得到了这个结果:
Traceback (most recent call last):
File "tija_v0.1.py", line 584, in <module>
loop.run_until_complete(asyncio.gather(*tasks))
File "C:\Dev\Anaconda2\envs\python36\lib\asyncio\tasks.py", line 589, in gather
fut = ensure_future(arg, loop=loop)
File "C:\Dev\Anaconda2\envs\python36\lib\asyncio\tasks.py", line 513, in ensure_future
task = loop.create_task(coro_or_future)
File "C:\Dev\Anaconda2\envs\python36\lib\asyncio\base_events.py", line 282, in create_task
self._check_closed()
File "C:\Dev\Anaconda2\envs\python36\lib\asyncio\base_events.py", line 357, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
sys:1: RuntimeWarning: coroutine 'value_2' was never awaited
sys:1: RuntimeWarning: coroutine 'value_1' was never awaited