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

相关推荐
速盾cdn1 小时前
速盾:如何判断高防服务器的防御是否真实?
网络·安全
ZachOn1y2 小时前
计算机网络:计算机网络体系结构 —— 专用术语总结
网络·tcp/ip·计算机网络·考研必备
笑非不退2 小时前
网络安全 网络安全的主要领域 安全威胁 防护技术 安全策略 未来趋势
网络
一尘之中2 小时前
网 络 安 全
网络·人工智能·学习·安全
qq_51583806 彩雷王3 小时前
1004-05,使用workflow对象创建http任务,redis任务
redis·网络协议·http
车载诊断技术4 小时前
什么是汽车中的SDK?
网络·架构·汽车·soa·电子电器架构
一颗星星辰4 小时前
Python | 第九章 | 排序和查找
服务器·网络·python
ZachOn1y4 小时前
计算机网络:计算机网络概述:网络、互联网与因特网的区别
网络·计算机网络·知识点汇总·考研必备
GOTXX5 小时前
应用层协议HTTP
linux·网络·网络协议·计算机网络·http·fiddler
小堃学编程12 小时前
计算机网络(十) —— IP协议详解,理解运营商和全球网络
网络·tcp/ip·计算机网络