三人组的WebSocket库
trio-websocket的Python项目详细描述
三个WebSocket
这个库实现了the WebSocket protocol,力求安全, 正确,符合人体工程学。它基于wsproto project,它是 Sans-IO实现 大多数WebSocket协议,包括帧、编解码器和事件。这个 库使用the Trio framework处理I/O。这个图书馆通过 Autobahn Test Suite。
本自述包含对项目的简要介绍。完整文档is available here。
安装
此库需要Python3.5或更高版本。从pypi安装:
pip install trio-websocket
客户示例
此示例演示如何打开WebSocket URL:
importtriofromsysimportstderrfromtrio_websocketimportopen_websocket_urlasyncdefmain():try:asyncwithopen_websocket_url('wss://echo.websocket.org')asws:awaitws.send_message('hello world!')message=awaitws.get_message()print('Received message: %s'%message)exceptOSErrorasose:print('Connection attempt failed: %s'%ose,file=stderr)trio.run(main)
WebSocket上下文管理器在进入块之前自动连接 并在退出块之前自动断开连接。完整的api提供了 大量的灵活性和额外的选择。
服务器示例
websocket服务器需要绑定地址、端口和协同路由来处理 传入连接。这个例子演示了一个“echo服务器”,它可以回复 每个传入消息都具有相同的传出消息。
importtriofromtrio_websocketimportserve_websocket,ConnectionClosedasyncdefecho_server(request):ws=awaitrequest.accept()whileTrue:try:message=awaitws.get_message()awaitws.send_message(message)exceptConnectionClosed:breakasyncdefmain():awaitserve_websocket(echo_server,'127.0.0.1',8000,ssl_context=None)trio.run(main)
服务器的处理程序echo_server(…)
接收连接请求对象。
此对象可用于检查客户端的请求并修改
握手,然后可以将其交换为实际的websocket对象ws
。
同样,完整的API提供了很多灵活性和附加选项。