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连接:

相关推荐
Kevin Wang72714 小时前
欧拉系统服务部署注意事项
网络·windows
min18112345615 小时前
深度伪造内容的检测与溯源技术
大数据·网络·人工智能
汤愈韬15 小时前
NAT策略
网络协议·网络安全·security·huawei
汤愈韬15 小时前
Full Cone Nat
网络·网络协议·网络安全·security·huawei
今晚务必早点睡15 小时前
系统通信方式实战详解:HTTP、RPC、MQ、WebSocket 各用在什么场景?(附 SDK 示例)
websocket·http·rpc
zbtlink15 小时前
现在还需要带电池的路由器吗?是用来干嘛的?
网络·智能路由器
桌面运维家16 小时前
vDisk配置漂移怎么办?VOI/IDV架构故障快速修复
网络·架构
dalerkd16 小时前
忙里偷闲叙-谈谈最近两年
网络·安全·web安全
汤愈韬16 小时前
NAT ALG (应用层网关)
网络·网络协议·网络安全·security·huawei
运维栈记18 小时前
虚拟化网络的根基-网络命名空间
网络·docker·容器