栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Python 3.6上的Websocket客户端中发出监听传入消息的问题

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Python 3.6上的Websocket客户端中发出监听传入消息的问题

最后,根据此帖子的答案,我以这种方式修改了客户端和主文件:

WebSocket客户端:

import websocketsimport asyncioclass WebSocketClient():    def __init__(self):        pass    async def connect(self):        ''' Connecting to webSocket server websockets.client.connect returns a WebSocketClientProtocol, which is used to send and receive messages        '''        self.connection = await websockets.client.connect('ws://127.0.0.1:8765')        if self.connection.open: print('Connection stablished. Client correcly connected') # Send greeting await self.sendMessage('Hey server, this is webSocket client') return self.connection    async def sendMessage(self, message):        ''' Sending message to webSocket server        '''        await self.connection.send(message)    async def receiveMessage(self, connection):        ''' Receiving all server messages and handling them        '''        while True: try:     message = await connection.recv()     print('Received message from server: ' + str(message)) except websockets.exceptions.ConnectionClosed:     print('Connection with server closed')     break    async def heartbeat(self, connection):        '''        Sending heartbeat to server every 5 seconds        Ping - pong messages to verify connection is alive        '''        while True: try:     await connection.send('ping')     await asyncio.sleep(5) except websockets.exceptions.ConnectionClosed:     print('Connection with server closed')     break

主要:

import asynciofrom webSocketClient import WebSocketClientif __name__ == '__main__':    # Creating client object    client = WebSocketClient()    loop = asyncio.get_event_loop()    # Start connection and get client connection protocol    connection = loop.run_until_complete(client.connect())    # Start listener and heartbeat     tasks = [        asyncio.ensure_future(client.heartbeat(connection)),        asyncio.ensure_future(client.receiveMessage(connection)),    ]    loop.run_until_complete(asyncio.wait(tasks))

现在,客户端可以继续监听来自服务器的所有消息,并每5秒向服务器发送“ ping”消息。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/429236.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号