我尝试使用来自此处的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()
要测试传入消息侦听器,服务器在建立连接时会向客户端发送两条消息。
客户端正确连接到服务器,然后发送问候语。但是,当客户端收到这两条消息时,它会引发一个带有代码1000的 ConnectionClosed异常(没有理由)。
如果我在receiveMessage客户端方法中删除循环,客户端不会引发任何异常,但它只收到一条消息,所以我想我需要一个循环来让监听器保持活跃,但我不确切知道或者如何。
任何解决方案?
提前致谢。
编辑:我意识到客户端在收到来自服务器的所有待处理消息时会关闭连接(并中断循环)。但是,我希望客户端能够继续监听未来的消息。
此外,我还尝试添加另一项功能,其任务是发送心跳'到服务器,但客户端仍然关闭连接。
答案 0 :(得分: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”消息。