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

相关推荐
侯小啾4 小时前
理解计算机网络中的MAC地址
网络·计算机网络·macos·mac
甄心爱学习4 小时前
计算机网络12
运维·服务器·网络
swanwei5 小时前
量子科技对核心产业的颠覆性影响及落地时间表(全文2500字)
大数据·网络·人工智能·程序人生·量子计算
大、男人6 小时前
目标URL存在http host头攻击漏洞
网络·网络协议·http
运维行者_7 小时前
网站出现 525 错误(SSL 握手失败)修复指南
服务器·网络·数据库·redis·网络协议·bootstrap·ssl
dreamtm1238 小时前
TCP 滑动窗口:像 “批量寄快递 + 收件人调速” 的高效协作
服务器·网络·tcp/ip
阿珊和她的猫11 小时前
WebSocket 与轮询:实时通信技术的对比与选择
网络·websocket·网络协议
生活爱好者!11 小时前
效率高!开源协作 Wiki 与文档管理平台 NAS一键部署docmost
运维·网络·docker·容器·开源
ao_lang12 小时前
UDP协议和TCP协议
网络协议·tcp/ip·udp