python使用websocket服务传输数据的例子,可以保持长连接

因为我们发短信(http)久了,所以我们希望有电话(websocket);有了电话之后,我们可以愉悦交通(双工通信),所以我们说着一句一句话(网络的一个一个包);为了能让对方清楚理解我们的意思,所以我们说的话阴阳顿挫,稍有停顿(包的长度),好让对方get到我们的点。

先安装websocket依赖:

复制代码
pip install websockets

websocket服务端:

python 复制代码
#!/usr/bin/env python

import asyncio
import websockets


async def echo(websocket):
    while True:
        name = await websocket.recv()
        print(f"接收到消息:{name}")
        replay = f"Hello {name}"
        await websocket.send(replay)
        print(f"发送消息结束")


async def main():
    async with websockets.serve(echo, "localhost", 8765):
        print("服务端启动成功:ws://localhost:8765")
        await asyncio.Future()  # run forever


asyncio.run(main())

websocket客户端:

python 复制代码
#!/usr/bin/env python

import asyncio
import time
import websockets


async def hello():
    async with websockets.connect("ws://localhost:8765") as websocket:
        while True:
            await websocket.send("Hello world!")
            message = await websocket.recv()
            print(f"Received: {message}")
            time.sleep(1)


asyncio.get_event_loop().run_until_complete(hello())

先运行服务端,然后运行客户端:

然后启动客户端:

或者也可以使用postman连接:

相关推荐
LUCIAZZZ10 分钟前
HTTPS优化简单总结
网络·网络协议·计算机网络·http·https·操作系统
wanhengidc22 分钟前
云手机运行流畅,秒开不卡顿
运维·网络·科技·游戏·智能手机
名誉寒冰1 小时前
TCP 拥塞控制与四次挥手解析
网络·网络协议·tcp/ip
笨小孩@GF 知行合一1 小时前
OSPF实验:外部路由引入
运维·网络·hcip·数通·ospf
Fireplusplus1 小时前
TCP MSS
网络·网络协议·tcp/ip
asdfg12589631 小时前
为什么要在出口路由器router配置NAT与默认路由
运维·网络·计算机网络
希赛网1 小时前
华为认证HCIA备考知识点 :IP路由基础(含配置案例)
网络·网络协议·计算机网络·路由交换
toooooop81 小时前
本地开发环境webScoket调试,保存html即用
前端·css·websocket
青草地溪水旁2 小时前
http response的工作流程详细解析
网络协议·http·应答
当归10242 小时前
SQL Server死锁排查实战指南
java·服务器·网络