为什么我收到" WebSocket连接已关闭:代码= 1000(OK),没有理由"

时间:2018-01-01 19:57:54

标签: python websocket

我有以下服务器:

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

P.S。已按照以下评论中的建议将while True添加到handler。但我仍然收到该错误

1 个答案:

答案 0 :(得分:2)

您没有启动服务器

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