要实现WebSocket客户端并封装代码,你可以使用Python的websockets
库。以下是一个简单的示例,演示了如何创建一个WebSocket客户端并对其进行封装:
import asyncio
import websockets
class WebSocketClient:
def __init__(self, uri):
self.uri = uri
self.websocket = None
async def connect(self):
self.websocket = await websockets.connect(self.uri)
print(f"Connected to {self.uri}")
async def send_message(self, message):
await self.websocket.send(message)
async def receive_message(self):
return await self.websocket.recv()
async def close(self):
await self.websocket.close()
print(f"Connection to {self.uri} closed")
# 使用示例
if __name__ == "__main__":
client = WebSocketClient("ws://localhost:8765")
asyncio.get_event_loop().run_until_complete(client.connect())
try:
while True:
message = input("Enter message to send (or type 'exit' to quit): ")
if message.lower() == "exit":
break
await client.send_message(message)
response = await client.receive_message()
print(f"Received response: {response}")
except KeyboardInterrupt:
pass
finally:
asyncio.get_event_loop().run_until_complete(client.close())
这个示例创建了一个WebSocketClient
类,它包含了connect
方法来连接到WebSocket服务器,send_message
方法来发送消息,receive_message
方法来接收消息,并在close
方法中关闭连接。你可以根据需要修改这些方法来适应你的业务逻辑。