当前位置:   article > 正文

【Python】基于asyncio的websocket服务器_基于asyncio的websocket server

基于asyncio的websocket server

机器环境

  • win10
  • python3.6
  • pip install ws4py

代码

  • ws_server.py
import asyncio
from ws4py.server.tulipserver import *
from ws4py.async_websocket import WebSocket

loop = asyncio.get_event_loop()

class WsServer(WebSocket):
    clients = set()

    def opened(self):
        print("new connection...")
        self.clients.add(self)

    def received_message(self, m):
        print("send msg...")
        for client in self.clients:
            client.send(m)

    def closed(self, code, reason="Error"):
        print("connect close...")


def init_server(host, port):
    factory = lambda: WebSocketProtocol(WsServer)
    return loop.create_server(factory, host, port)


def main():
    ws_server = loop.run_until_complete(init_server('localhost', 9007))
    print('serving on', ws_server.sockets[0].getsockname())
    loop.run_forever()

if __name__ == '__main__':
    main()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/85377
推荐阅读
相关标签
  

闽ICP备14008679号