如果有多个用户尝试连接,那么websockets如何工作?

时间:2018-02-01 15:09:38

标签: python python-3.x sockets websocket python-asyncio

我知道如何在Python中创建一个websocket服务器,如下所述:

Why do I receive "WebSocket connection is closed: code = 1000 (OK), no reason"

根据我对TCP套接字的了解,我需要创建一个被动Socket,并为每个客户端创建一个活动的Socket - 这个代码是否与此代码相同?

示例服务器代码:

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

示例客户端代码:

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

客户端最终将成为一个应用程序,但我无法同时与多个用户进行测试,因此这个问题。

0 个答案:

没有答案