python websockets 全双工通信

python websockets全双工通信

功能描述

客户端和服务端都可发送或接收数据。发送和接收相互独立,异步并发。

运行环境

python3.6.8

websockets9.1

服务端

import asyncio
import websockets

async def send(websocket):
    while True:
        await asyncio.sleep(1)
        #此协程挂起1s,以切换到其他协程。不加此行不会切换到另一个协程。此处用time.sleep()不能起到这个作用。
	    #可以在此产生数据然后send出去。	
        await websocket.send("hello")
        #正常地发送,不会切换到receive()
        print("send hello")


async def receive(websocket):
    while True:
        await asyncio.sleep(1)
        #此协程挂起1s,以切换到其他协程。不加此行不会切换到另一个协程。此处用time.sleep()不能起到这个作用。
        greeting = await websocket.recv()
        #正常地接收,不会切换到send()
        print("receive "+greeting)


async def hello(websocket, path):
        a = asyncio.get_event_loop().create_task(send(websocket))
        b = asyncio.get_event_loop().create_task(receive(websocket))
        #使用create_task()创建task

        await a
        await b
        # ab并发
        # ab并发,下面这行代码不会执行
        print("wait")
        #print("wait")不会执行

start_server = websockets.serve(hello, "localhost", 8766)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

客户端

import asyncio
import websockets

async def send(websocket):
    while True:
        await asyncio.sleep(1)
        #此协程挂起1s,以切换到其他协程。不加此行不会切换到另一个协程。此处用time.sleep()不能起到这个作用。

        await websocket.send("hello")
        #正常地发送,不会切换到receive()

        print("send hello")


async def receive(websocket):
    while True:
        await asyncio.sleep(1)
        #此协程挂起1s,以切换到其他协程。不加此行不会切换到另一个协程。此处用time.sleep()不能起到这个作用。

        greeting = await websocket.recv()
        #正常地接收,不会切换到send()
        print("receive"+greeting)


async def hello():
    uri = "ws://localhost:8766"
    async with websockets.connect(uri) as websocket:
        a = asyncio.get_event_loop().create_task(send(websocket))
        b = asyncio.get_event_loop().create_task(receive(websocket))
        await a
        await b
        # ab并发,下面这行代码不会执行
        print("wait")
        #print("wait")不会执行

asyncio.get_event_loop().run_until_complete(hello())
  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值