websockets库使用(基于Python)

主要参考资料:

【Python】websockets库的介绍及用法: https://blog.csdn.net/qq_53871375/article/details/135920231

python模块websockets,浏览器与服务器之间的双向通信: https://blog.csdn.net/randy521520/article/details/134752051

目录

  • websockets库
    • [创建 WebSocket 服务器](#创建 WebSocket 服务器)
    • [创建 WebSocket 客户端](#创建 WebSocket 客户端)
    • 广播消息
    • [SSL/TLS 加密](#SSL/TLS 加密)

websockets库

websockets库 是一个基于 asyncio 的 Python 库,旨在提供简单易用的 WebSockets 服务器和客户端功能。有如下特性:

  • 简单易用:提供简洁的 API,方便快速上手。
  • 基于 asyncio:利用 Python 的 asyncio 库实现异步 I/O 操作,支持高并发。
  • 全双工通信:支持在单个连接上同时进行数据发送和接收。
  • 支持多种协议:兼容 WebSocket 协议,支持 SSL/TLS 加密。
  • 灵活扩展:支持自定义协议和中间件,方便扩展功能。

创建 WebSocket 服务器

可以使用 websockets.serve 创建一个简单的 WebSocket 服务器:

websockets.serve(): 这个函数负责创建并启动一个WebSocket服务器。

websocket.recv(): 这个函数是一个协程函数,用于从WebSocket接收消息。

websocket.send(): 这个函数是一个协程函数,用于向WebSocket发送消息。

python 复制代码
import asyncio
import websockets
 
async def hello(websocket, path):
    name = await websocket.recv()
    print(f"< {name}")
    
    greeting = f"Hello {name}!"
    
    await websocket.send(greeting)
    print(f"> {greeting}")
 
start_server = websockets.serve(hello, "localhost", 8765)
 
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

创建 WebSocket 客户端

可以使用 websockets.connect 创建一个简单的 WebSocket 客户端:

websockets.connect(): 这个函数负责创建一个 WebSocket 客户端。

websocket.close(): 关闭 WebSocket 连接。

websockets.exceptions: 提供了WebSocket特定的异常。如:ConnectionClosed、InvalidHandshake、InvalidOrigin等。

python 复制代码
import asyncio
import websockets
 
async def hello():
    uri = "ws://localhost:8765"
    async with websockets.connect(uri) as websocket:
        await websocket.send("Hello, World!")
        response = await websocket.recv()
        print(f"< {response}")
 
asyncio.get_event_loop().run_until_complete(hello())

广播消息

可以实现消息广播功能,将消息发送给所有连接的客户端:

python 复制代码
import asyncio
import websockets
 
connected_clients = set()
 
async def handler(websocket, path):
    connected_clients.add(websocket)
    try:
        async for message in websocket:
            await asyncio.wait([client.send(message) for client in connected_clients])
    finally:
        connected_clients.remove(websocket)
 
start_server = websockets.serve(handler, "localhost", 8765)
 
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

SSL/TLS 加密

可以为 WebSocket 服务器添加 SSL/TLS 加密,确保数据传输安全:

python 复制代码
import asyncio
import ssl
import websockets
 
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain(certfile="path/to/certfile", keyfile="path/to/keyfile")
 
async def echo(websocket, path):
    async for message in websocket:
        await websocket.send(message)
 
start_server = websockets.serve(echo, "localhost", 8765, ssl=ssl_context)
 
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
相关推荐
Fairy_sevenseven9 分钟前
【二十八】【QT开发应用】模拟WPS Tab
开发语言·qt·wps
蜡笔小新星17 分钟前
Python Kivy库学习路线
开发语言·网络·经验分享·python·学习
凯子坚持 c17 分钟前
C语言复习概要(三)
c语言·开发语言
无限大.28 分钟前
c语言200例 067
java·c语言·开发语言
余炜yw30 分钟前
【Java序列化器】Java 中常用序列化器的探索与实践
java·开发语言
篝火悟者31 分钟前
问题-python-运行报错-SyntaxError: Non-UTF-8 code starting with ‘\xd5‘ in file 汉字编码问题
开发语言·python
Death20034 分钟前
Qt 中的 QListWidget、QTreeWidget 和 QTableWidget:简化的数据展示控件
c语言·开发语言·c++·qt·c#
六点半88835 分钟前
【C++】速通涉及 “vector” 的经典OJ编程题
开发语言·c++·算法·青少年编程·推荐算法
惜.己35 分钟前
javaScript基础(8个案例+代码+效果图)
开发语言·前端·javascript·vscode·css3·html5
niu_sama39 分钟前
基于muduo库函数实现protobuf协议的通信
开发语言·qt