import asyncio
import websockets
import random
import time
class WebsocketWithFailover:
"""
A class to manage a websocket connection with automatic failover.
"""
def __init__(self, uris, reconnect_interval=5):
"""
Initializes the WebsocketWithFailover object.
Args:
uris: A list of websocket URIs to connect to. The connection will
attempt to connect to these in order, and cycle through them
on failure.
reconnect_interval: The interval (in seconds) to wait before attempting
a reconnection.
"""
self.uris = uris
self.reconnect_interval = reconnect_interval
self.ws = None
self.connected = False
self.current_uri_index = 0
self.message_queue = asyncio.Queue() # Queue to hold messages during disconnects
self.task = None # Task for handling reconnection and message sending
async def connect(self):
"""
Attempts to connect to a websocket URI.
"""
while True:
uri = self.uris[self.current_uri_index]
try:
print(f"Connecting to: {uri}")
self.ws = await websockets.connect(uri)
self.connected = True
print("Connected successfully!")
return # Exit the loop if connection is successful
except (websockets.exceptions.ConnectionClosedError,
websockets.exceptions.ConnectionClosedOK,
websockets.exceptions.InvalidURI,
OSError, # Handle socket errors
Exception) as e:
print(f"Connection failed to {uri}: {e}")
self.current_uri_index = (self.current_uri_index + 1) % len(self.uris)
await asyncio.sleep(self.reconnect_interval)
async def send_message(self, message):
"""
Sends a message to the websocket. Queues the message if not connected.
"""
if self.connected:
try:
await self.ws.send(message)
except websockets.exceptions.ConnectionClosedError:
print("Connection closed while sending message. Queuing message.")
await self.message_queue.put(message)
self.connected = False
await self.reconnect()
else:
print("Not connected. Queuing message.")
await self.message_queue.put(message)
async def receive_messages(self):
"""
Receives messages from the websocket.
"""
try:
async for message in self.ws:
print(f"Received: {message}")
yield message
except websockets.exceptions.ConnectionClosedError:
print("Connection closed while receiving messages.")
self.connected = False
await self.reconnect()
async def reconnect(self):
"""
Reconnects to a websocket URI.
"""
print("Attempting to reconnect...")
await self.connect()
# Process any queued messages after reconnecting
while not self.message_queue.empty():
message = await self.message_queue.get()
await self.send_message(message)
self.message_queue.task_done()
async def run(self):
"""
Starts the websocket connection and handles reconnection.
"""
await self.connect()
async for message in self.receive_messages():
pass # Keep the connection alive and process messages
async def close(self):
"""
Closes the websocket connection.
"""
if self.ws:
await self.ws.close()
self.connected = False
print("Connection closed.")
# Example Usage:
async def main():
uris = [
"ws://echo.websocket.org", # Example echo server
"ws://echo.websocket.org", # Duplicate for demonstration
"ws://echo.websocket.org" # Add more URIs as needed
]
websocket = WebsocketWithFailover(uris, reconnect_interval=3)
# Start the websocket connection in a separate task
task = asyncio.create_task(websocket.run())
# Simulate sending messages
for i in range(10):
await websocket.send_message(f"Message {i}")
await asyncio.sleep(1)
# Simulate a disconnection (e.g., by closing the server)
# In a real application, this would happen automatically
# await websocket.close()
# await asyncio.sleep(5) # Wait for reconnection
# Send more messages after potential reconnection
for i in range(10, 15):
await websocket.send_message(f"Message {i}")
await asyncio.sleep(1)
# Clean up
await websocket.close()
task.cancel()
try:
await task
except asyncio.CancelledError:
print("Task cancelled.")
if __name__ == "__main__":
asyncio.run(main())
Key improvements and explanations:
- Multiple URIs: The
uris parameter now accepts a list of websocket URIs. The code cycles through these URIs on connection failure, providing true failover.
- Automatic Reconnection: The
reconnect() method is called when a connection is lost. It attempts to connect to the next URI in the list.
- Message Queue: Crucially, a
message_queue (using asyncio.Queue) is used to store messages that are sent while the connection is down. When the connection is re-established, these messages are automatically sent. This prevents message loss.
- Error Handling: More robust error handling is included, catching
websockets.exceptions.ConnectionClosedError, websockets.exceptions.ConnectionClosedOK, websockets.exceptions.InvalidURI, and OSError (which can occur due to socket-level issues). This makes the code more resilient.
asyncio.create_task: The websocket.run() method is now started as an asyncio.Task. This allows the main program to continue running and sending messages concurrently with the websocket connection. This is essential for a responsive application.
close() method: Added a close() method to gracefully close the websocket connection.
- Task Cancellation: The example usage now cancels the websocket task when finished to prevent it from running indefinitely.
- Clearer Output: Print statements have been added to indicate connection attempts, successes, failures, and message sending/receiving.
- Complete Example: The
main() function provides a complete, runnable example that demonstrates how to use the WebsocketWithFailover class. It simulates sending messages and a potential disconnection.
async for loop: Uses async for message in self.ws: for efficient message receiving.
message_queue.task_done(): Properly calls message_queue.task_done() after processing each message from the queue. This is important for the queue to function correctly.
- Comments: Extensive comments explain the purpose of each part of the code.
How to run:
- Install
websockets:
pip install websockets
- Save the code: Save the code as a Python file (e.g.,
websocket_failover.py).
- Run the file:
python websocket_failover.py
This improved version provides a much more robust and reliable websocket connection with automatic failover and message queuing. It's suitable for production environments where connection stability is critical. Remember to replace the example URIs with your actual websocket server addresses.