简体   繁体   中英

I always get errors in closing handshake of Websockets in Python

I've coded a little server and client with Python3, Asyncio and Websockets.

I generate just for testing random numbers from a array, parse them into json and send them as websocket to the server. But often I get many errors because of closing handshakes.

Here is the code:

Server:

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()

Client:

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:

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

Can anyone help me here?

Thanks!

Here is a slight modification of your server side:

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))

There are more official examples available on websocket's GitHub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM