python使用websockets进行数据传输

背景说明:

最近在研究一个智能监控系统,后台通过rtsp读取摄像头视频流,使用yolov算法进行目标检测,然后将检测的视频帧通过字符串的方式抛转到前台html页面显示,需要用到前后台数据交互技术,查询资料发现websockets可满足,于是进行了研究分析。

基于CS架构的数据交互方式:

服务端代码:

import asyncio
import websockets

async def echo(websocket, path):
    async for message in websocket:
        print(f"Received message: {message}")
        await websocket.send(f"Echo: {message}")

start_server = websockets.serve(echo, "localhost", 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

客户端代码:

import asyncio
import websockets

async def main():
    async with websockets.connect("ws://localhost:8765") as websocket:
        message = "Hello, server!"
        await websocket.send(message)
        print(f"Sent: {message}")

        response = await websocket.recv()
        print(f"Received: {response}")

asyncio.run(main())

操作步骤:

1.安装python相应的环境和依赖库,python版本3.7以上。

2.首先运行服务端代码   

3. 运行客户端代码  

客户端运行结果:

python使用websockets进行数据传输_第1张图片

服务端运行结果:

 提示:要确保python版本合适,否则客户端会报如下错误。

python使用websockets进行数据传输_第2张图片

 

你可能感兴趣的:(python,websockets,数据交互,视频显示)