最后,根据此帖子的答案,我以这种方式修改了客户端和主文件:
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”消息。



