• Python——eventlet.websocket


      使用该模块可以方便地创建 websocket 服务器,要创建一个websocket服务器,只需要将一个句柄函数用装饰器 WebSocketWSGI 装饰即可,然后这个函数就可以当做一个WSGI应用:

    from eventlet import wsgi, websocket
    import eventlet
    
    @websocket.WebSocketWSGI
    def hello_world(ws):
        ws.send("hello world")
    
    wsgi.server(eventlet.listen(('', 8090)), hello_world)
    

      注:Please see graceful termination warning in server() documentation

      You can find a slightly more elaborate version of this code in the file examples/websocket.py.

      As of version 0.9.13, eventlet.websocket supports SSL websockets; all that’s necessary is to use an SSL wsgi server.

     class eventlet.websocket.WebSocketWSGI(handler) 

      在一个 WSGI 应用中包裹一个websocket句柄函数

      示例:

    @websocket.WebSocketWSGI
    def my_handler(ws):
        from_browser = ws.wait()
        ws.send("from server")
    

      参数是 WebSocket 实例,从函数中返回就会关闭 socket,服务器会在关闭时记录websocket的请求

     class eventlet.websocket.WebSocket(sock, environ, version=76) 

      一个 websocket 对象,处理套接字的 serialization/deserialization 细节

      与一个 WebSocket 对象交互的主要手段是调用 send() 和 wait(),通过该调用可以与浏览器之间进行消息传递,下面的属性也可用:

      path 

      请求的路径值,等同于 WSGI PATH_INFO 变量,但是更方便

      protocol 

      Websocket-Protocol 头字段的值

      origin 

      ‘Origin’ 头字段的值

      environ 

      该请求的完整 WSGI 环境

      close() 

      强制关闭 websocket; generally it is preferable to return from the handler method.

      send(message) 

      向浏览器发送一个消息

      message 应被转化成一个字符串, unicode 对象应被编码为 utf-8。如果套接字已经被客户端关闭,抛出异常 socket.error 和 errno 32 (broken pipe)

      wait() 

      等待和反序列化消息

      返回最久没有被处理的那条消息。如果客户端关闭了连接,返回 None,不同于普通的套接字行为因为空字符串也是有效的websocket消息。

  • 相关阅读:
    UVA11584 划分成回文串
    UVA1220Party at Hali-Bula(树的最大独立集 + 唯一性判断)
    BUAA1389愤怒的DZY(最大值最小化)
    九度1502 最大值最小化问题
    App(4.25)
    App(4.24)
    App(4.23)
    App(4.22)
    学习进度条(八)
    App(4.21)
  • 原文地址:https://www.cnblogs.com/Security-Darren/p/4168321.html
Copyright © 2020-2023  润新知