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


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

    先安装websocket依赖:

    pip install websockets

    websocket服务端:

    1. #!/usr/bin/env python
    2. import asyncio
    3. import websockets
    4. async def echo(websocket):
    5. while True:
    6. name = await websocket.recv()
    7. print(f"接收到消息:{name}")
    8. replay = f"Hello {name}"
    9. await websocket.send(replay)
    10. print(f"发送消息结束")
    11. async def main():
    12. async with websockets.serve(echo, "localhost", 8765):
    13. print("服务端启动成功:ws://localhost:8765")
    14. await asyncio.Future() # run forever
    15. asyncio.run(main())

     websocket客户端:

    1. #!/usr/bin/env python
    2. import asyncio
    3. import time
    4. import websockets
    5. async def hello():
    6. async with websockets.connect("ws://localhost:8765") as websocket:
    7. while True:
    8. await websocket.send("Hello world!")
    9. message = await websocket.recv()
    10. print(f"Received: {message}")
    11. time.sleep(1)
    12. asyncio.get_event_loop().run_until_complete(hello())

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

    然后启动客户端: 

    或者也可以使用postman连接:

     

  • 相关阅读:
    bean的自动装配
    编译器工程师眼中的好代码:Loop Interchange
    selenium自动化测试-获取黄金实时价格
    零拷贝、MMAP、堆外内存
    Spring 从入门到精通 (十) 复杂对象详解
    Fbank及MFCC学习
    wordpress插件-免费的wordpress全套插件
    nginx
    java 处理日期的方法
    Proxmox VE 镜像定制化
  • 原文地址:https://blog.csdn.net/weixin_44786530/article/details/133039802