我正在尝试使用来自此处的 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))
Run Code Online (Sandbox Code Playgroud)
这是主要的:
'''
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()
Run Code Online (Sandbox Code Playgroud)
为了测试传入消息侦听器,服务器在建立连接时向客户端发送两条消息。
客户端正确连接到服务器,并发送问候语。但是,当客户端收到两条消息时,它会引发一个ConnectionClosed 异常,代码为 1000(无缘无故)。
如果我删除 receiveMessage 客户端方法中的循环,客户端不会引发任何异常,但它只接收一条消息,所以我想我需要一个循环来保持侦听器处于活动状态,但我不知道确切的位置或方式。
有什么解决办法吗?
提前致谢。
编辑:我意识到客户端在收到来自服务器的所有待处理消息时关闭连接(并中断循环)。但是,我希望客户端保持活动状态,收听未来的消息。
此外,我尝试添加另一个函数,其任务是向服务器发送“心跳”,但客户端无论如何都会关闭连接。
Cha*_*low 18
最后,基于这个帖子的答案,我以这种方式修改了我的客户端和主文件:
网络套接字客户端:
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
Run Code Online (Sandbox Code Playgroud)
主要的:
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))
Run Code Online (Sandbox Code Playgroud)
现在,客户端保持活动状态,监听来自服务器的所有消息,并每 5 秒向服务器发送 'ping' 消息。
| 归档时间: |
|
| 查看次数: |
9364 次 |
| 最近记录: |