为啥我会收到“WebSocket 连接已关闭:代码 = 1000(OK),没有原因”
Posted
技术标签:
【中文标题】为啥我会收到“WebSocket 连接已关闭:代码 = 1000(OK),没有原因”【英文标题】:Why do I receive "WebSocket connection is closed: code = 1000 (OK), no reason"为什么我会收到“WebSocket 连接已关闭:代码 = 1000(OK),没有原因” 【发布时间】:2018-01-01 19:57:53 【问题描述】:我有以下服务器:
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())
时,我收到以下错误:
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
。但我仍然收到该错误
【问题讨论】:
【参考方案1】:你没有启动服务器
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()
【讨论】:
没有帮助。我已经创建了 app.py,它仍然会收到 1000... 错误 这很奇怪吗?这在 python3.6 上运行良好。能不能加app.py代码。 已添加。我也尝试使用 python 3.6 keeping connections open 尝试在处理函数中添加一个while循环。while = True: async for message ..
现在 print()
有效,但 await websocket.send(message)
失败并出现 1000 错误以上是关于为啥我会收到“WebSocket 连接已关闭:代码 = 1000(OK),没有原因”的主要内容,如果未能解决你的问题,请参考以下文章