olnm 发表于 2015-12-1 11:34:42

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消息。
页: [1]
查看完整版本: Python——eventlet.websocket