【问题标题】:Issues listening incoming messages in websocket client on Python 3.6在 Python 3.6 上的 websocket 客户端中监听传入消息的问题
【发布时间】:2018-09-27 11:17:48
【问题描述】:

我正在尝试使用此处的 websockets 包在 Python 上构建 websocket 客户端:Websockets 4.0 API

我使用这种方式而不是示例代码,因为我想创建一个 websocket 客户端类对象,并将其用作网关。

我在客户端的侦听器方法 (receiveMessage) 有问题,这会在执行时引发 ConnectionClose 异常。我认为循环可能有任何问题。

这是我尝试构建的简单 webSocket 客户端:

import websockets

class 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')
            # Enable listener
            await self.receiveMessage()


    async def sendMessage(self, message):
        '''
            Sending message to webSocket server
        '''
        await self.connection.send(message)

    async def receiveMessage(self):
        '''
            Receiving all server messages and handling them
        '''
        while True:
            message = await self.connection.recv()
            print('Received message from server: ' + str(message))

这是主要的:

'''
    Main file
'''

import asyncio
from webSocketClient import WebSocketClient

if __name__ == '__main__':
    # Creating client object
    client = WebSocketClient()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(client.connect())
    loop.run_forever()
    loop.close()

为了测试传入消息侦听器,服务器在建立连接时向客户端发送两条消息。

客户端正确连接到服务器,并发送问候语。但是,当客户端收到两条消息时,它会引发 ConnectionClosed 异常,代码为 1000(没有原因)。

如果我在 receiveMessage 客户端方法中删除循环,客户端不会引发任何异常,但它只接收一条消息,所以我想我需要一个循环来保持侦听器处于活动状态,但我不知道确切的位置或方式.

有什么解决办法吗?

提前致谢。

编辑:我意识到客户端在收到来自服务器的所有待处理消息时会关闭连接(并中断循环)。但是,我希望客户能够继续聆听未来的消息。

此外,我尝试添加另一个函数,其任务是向服务器发送“心跳”,但客户端仍然关闭连接。

【问题讨论】:

    标签: python websocket


    【解决方案1】:

    最后,基于这个post 的回答,我这样修改了我的客户端和主文件:

    WebSocket 客户端:

    import websockets
    import asyncio
    
    class 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 asyncio
    from webSocketClient import WebSocketClient
    
    if __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' 消息。

    【讨论】:

      猜你喜欢
      • 2021-07-06
      • 1970-01-01
      • 2019-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      • 2015-06-18
      • 2011-10-28
      相关资源
      最近更新 更多