我总是在Python中关闭Websockets的握手时遇到错误

时间:2018-03-23 23:14:15

标签: python asynchronous websocket async-await

我用Python3,Asyncio和Websockets编写了一个小服务器和客户端。

我生成的只是用于测试数组中的随机数,将它们解析为json并将它们作为websocket发送到服务器。但是,由于结束握手,我经常会遇到很多错误。

以下是代码:

服务器:

import asyncio
import websockets
import json


async def receiver(websocket, path):
    ws = await websocket.recv()
    print("< {}".format(ws))


start_server = websockets.serve(receiver, 'localhost', 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

客户端:

import asyncio
import websockets
import json
from array import *
import random


async def randomNumbers():
    while True:
        numbers = array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9])
        random.shuffle(numbers)
        await sendWebsocket(numbers[0])
        await asyncio.sleep(1)


async def sendWebsocket(number):
    async with websockets.connect('ws://localhost:8765') as websocket:
        ws = json.dumps({"number": number})
        await websocket.send(ws)
        print("> {}".format(ws))


loop = asyncio.get_event_loop()
try:
    asyncio.ensure_future(randomNumbers())
    loop.run_forever()
finally:
    print("Client1 closed")
    loop.close()

错误:

Error in closing handshake
Traceback (most recent call last):
  File "C:\Users\dgred\AppData\Local\Programs\Python\Python36-32\lib\site-packages\websockets\server.py", line 145, in handler
    yield from self.close()
  File "C:\Users\dgred\AppData\Local\Programs\Python\Python36-32\lib\site-packages\websockets\protocol.py", line 370, in close
    self.timeout, loop=self.loop)
  File "C:\Users\dgred\AppData\Local\Programs\Python\Python36-32\lib\asyncio\tasks.py", line 358, in wait_for
    return fut.result()
  File "C:\Users\dgred\AppData\Local\Programs\Python\Python36-32\lib\site-packages\websockets\protocol.py", line 642, in write_frame
    "in the {} state".format(self.state.name))
websockets.exceptions.InvalidState: Cannot write to a WebSocket in the CLOSING state

有人可以帮我吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

以下是服务器端的略微修改:

import asyncio
import websockets
import json
import signal

async def receiver(websocket, path):
   while True:
      try:
         ws = await websocket.recv()
         print("< {}".format(ws))
      except websockets.ConnectionClosed:
        print("Connection closed")
        break

async def simple_server(stop):
   async with websockets.serve(receiver, 'localhost', 8765):
      await stop

loop = asyncio.get_event_loop()

stop = asyncio.Future()
loop.add_signal_handler(signal.SIGTERM, stop.set_result, None)

loop.run_until_complete(simple_server(stop))

websocket's GitHub

上有更多官方示例