[英]I always get errors in closing handshake of Websockets in Python
我已經用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
有人能幫我一下嗎?
謝謝!
這是您的服務器端的略微修改:
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的GitHub上還有更多官方示例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.