为什么我收到“WebSocket connection is closed: code = 1000 (OK), no reason"? [英] Why do I receive "WebSocket connection is closed: code = 1000 (OK), no reason"
本文介绍了为什么我收到“WebSocket connection is closed: code = 1000 (OK), no reason"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下服务器:
import os
import asyncio
import websockets
class Server:
def get_port(self):
return os.getenv('WS_PORT', '8765')
def get_host(self):
return os.getenv('WS_HOST', 'localhost')
def start(self):
return websockets.serve(self.handler, self.get_host(), self.get_port())
async def handler(self, websocket, path):
while True:
async for message in websocket:
await websocket.send(message)
和客户:
import asyncio
import websockets
async def msg():
async with websockets.connect('ws://localhost:8765') as websocket:
await websocket.send('test message')
asyncio.get_event_loop().run_until_complete(msg())
当我执行 asyncio.get_event_loop().run_until_complete(msg())
时,我收到以下错误:
When I execute asyncio.get_event_loop().run_until_complete(msg())
I receive the following error:
websockets.exceptions.ConnectionClosed: WebSocket connection is closed: code = 1000 (OK), no reason
还有 app.py
代码:
#!/usr/bin/env python3.6
import asyncio
from server import Server
if __name__ == '__main__':
ws = Server()
asyncio.get_event_loop().run_until_complete(ws.start())
asyncio.get_event_loop().run_forever()
附言将 while True
添加到 handler
,如下面的评论中所建议.但我仍然收到那个错误
P.S. Added while True
to handler
as suggested in the comment below. But I still receive that error
推荐答案
你没有启动服务器
server.py
:
import os
import asyncio
import websockets
class Server:
def get_port(self):
return os.getenv('WS_PORT', '8765')
def get_host(self):
return os.getenv('WS_HOST', 'localhost')
def start(self):
return websockets.serve(self.handler, self.get_host(), self.get_port())
async def handler(self, websocket, path):
async for message in websocket:
print('server received :', message)
await websocket.send(message)
if __name__ == '__main__':
ws = Server()
asyncio.get_event_loop().run_until_complete(ws.start())
asyncio.get_event_loop().run_forever()
client.py
#!/usr/bin/env python3.6
import asyncio
import websockets
async def msg():
async with websockets.connect('ws://localhost:8765') as websocket:
await websocket.send('test message')
msg = await websocket.recv()
print(msg)
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(msg())
asyncio.get_event_loop().run_forever()
这篇关于为什么我收到“WebSocket connection is closed: code = 1000 (OK), no reason"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文