python的WebSocket收发消息

系统 2035 0

版权声明:转载请注明作者(独孤尚良dugushangliang)出处:https://blog.csdn.net/dugushangliang/article/details/100971395

 

参阅:https://websockets.readthedocs.io/en/stable/

先启动服务端:

            
              import asyncio
import websockets
port=8765
host='localhost'
print(f'ws://{host}:{port}')

async def deal(websocket,path):
        message=await websocket.recv()
        print(message)

start_server = websockets.serve(deal, host, port)
#下面这行代码执行后创建一个WebSocket对象
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
            
          

启动服务端后,将一直等待客户端的连接。

再执行客户端:

            
              import asyncio
import websockets
async def hello():
    uri = "ws://localhost:8765"
    async with websockets.connect(uri) as websocket:
            message=input('cin: ')
            print(f"< {message}")
            await websocket.send(message)

#下面代码一执行,客户端将和服务端建立连接。客户端将等待输入内容,输入后客户端即发送此内容到服务端
asyncio.get_event_loop().run_until_complete(hello())
            
          

上文的这个代码,决定了:客户端连接后只能发送消息并不能接收消息。客户端发送消息给服务端后,连接即停止。除非再次执行客户端的最后一行代码,重新建立连接。

那么,怎么实现,客户端能一直给服务端发送消息呢?

上loop

            
              async def hello():
    uri = "ws://localhost:8765"
    async with websockets.connect(uri) as websocket:
        while True:
            message=input('cin: ')
            if message=='esc':
                break
            print(f"< {message}")
            await websocket.send(message)
            
          

但有个问题:客户端发送一条消息后,虽然可以继续输入,但是服务端并不接收内容了。这是因为代码决定了服务端只接收一次。

那么怎么写代码,可以让服务端一直接收消息?

            
              async def deal(websocket,path):
    while True:
        message=await websocket.recv()
        print(message)
            
          

python的WebSocket收发消息_第1张图片

还有一种操作: 

            
              async def deal(websocket,path):
    async for message in websocket:
        message=await websocket.recv()
        print(message)
            
          

 

 

独孤尚良dugushangliang——著


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论