Python——eventlet.websocket

本文介绍如何使用Eventlet库创建WebSocket服务器。只需装饰句柄函数并将其作为WSGI应用运行即可。支持SSL WebSocket,并提供了与浏览器进行消息传递的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

  使用该模块可以方便地创建 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消息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值