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

相关推荐
xxy!18 分钟前
OSI七层模型和TCP/IP四层模型
网络·网络协议·tcp/ip
unique_pursuit28 分钟前
CS144 Lab 6 实战记录:构建 IP 路由器
网络·tcp/ip·智能路由器
掘金-我是哪吒2 小时前
分布式微服务系统架构第119集:WebSocket监控服务内部原理和执行流程
分布式·websocket·微服务·架构·系统架构
lllsure2 小时前
SpringCloud——负载均衡
服务器·网络·spring cloud
宝耶2 小时前
HTTP协议-请求协议
网络协议·http·servlet
撬动未来的支点5 小时前
【网络】TCP/IP协议学习
网络·学习·tcp/ip
掘金-我是哪吒5 小时前
分布式微服务系统架构第120集:专业WebSocket鉴权
分布式·websocket·微服务·云原生·架构
wqdian_com5 小时前
“广州丰田汽车.网址”中文域名仲裁案:“网络门牌”保护战
网络
草海桐5 小时前
go 的 net 包
网络·golang·net
lboyj5 小时前
5G/6G通信设备中的盲埋孔技术突破
网络