I'll help you create a WebSocket client with automatic failover/reconnection functionality in Python using the websockets library. Here's a robust implementation:
import asyncio
import websockets
import logging
from typing import Optional
import random
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class WebSocketClient:
def __init__(self, urls: list[str], retry_interval: tuple[int, int] = (1, 5)):
"""
Initialize WebSocket client with multiple server URLs for failover
Args:
urls: List of WebSocket server URLs
retry_interval: Tuple of (min, max) seconds to wait between reconnection attempts
"""
self.urls = urls
self.retry_interval = retry_interval
self.websocket: Optional[websockets.WebSocketClientProtocol] = None
self.current_url_index = 0
self.is_running = False
async def connect(self) -> None:
"""Establish WebSocket connection with automatic failover"""
while self.is_running:
try:
url = self.urls[self.current_url_index]
logger.info(f"Attempting to connect to {url}")
async with websockets.connect(url) as websocket:
self.websocket = websocket
logger.info(f"Connected to {url}")
await self.handle_connection()
except Exception as e:
logger.error(f"Connection error: {str(e)}")
await self.handle_disconnection()
async def handle_connection(self) -> None:
"""Handle the WebSocket connection and incoming messages"""
try:
while True:
message = await self.websocket.recv()
await self.process_message(message)
except websockets.ConnectionClosed:
logger.warning("WebSocket connection closed")
except Exception as e:
logger.error(f"Error in connection handler: {str(e)}")
async def handle_disconnection(self) -> None:
"""Handle disconnection and prepare for reconnection"""
self.websocket = None
# Move to next URL in the failover list
self.current_url_index = (self.current_url_index + 1) % len(self.urls)
# Wait before reconnecting
delay = random.uniform(self.retry_interval[0], self.retry_interval[1])
logger.info(f"Reconnecting in {delay:.1f} seconds...")
await asyncio.sleep(delay)
async def process_message(self, message: str) -> None:
"""Process received messages"""
logger.info(f"Received message: {message}")
# Add your message processing logic here
async def send_message(self, message: str) -> bool:
"""Send a message through the WebSocket connection"""
if self.websocket and not self.websocket.closed:
try:
await self.websocket.send(message)
return True
except Exception as e:
logger.error(f"Error sending message: {str(e)}")
return False
async def start(self) -> None:
"""Start the WebSocket client"""
self.is_running = True
await self.connect()
async def stop(self) -> None:
"""Stop the WebSocket client"""
self.is_running = False
if self.websocket:
await self.websocket.close()
# Example usage
async def main():
# List of WebSocket servers to try
urls = [
"ws://primary-server.com/websocket",
"ws://backup1-server.com/websocket",
"ws://backup2-server.com/websocket"
]
client = WebSocketClient(urls)
try:
# Start the client
await client.start()
except KeyboardInterrupt:
# Handle graceful shutdown
await client.stop()
if __name__ == "__main__":
asyncio.run(main())
This implementation includes several key features:
- Multiple server URLs for failover
- Automatic reconnection with exponential backoff
- Error handling and logging
- Message sending and receiving capabilities
- Clean shutdown handling
To use this code:
- Install required package:
pip install websockets
- Replace the example URLs with your actual WebSocket server URLs
- Customize the
process_message method to handle your specific message processing needs
- Add any additional error handling or business logic as needed
The client will automatically:
- Try to connect to the first URL in the list
- If connection fails, move to the next URL
- Implement random delay between reconnection attempts
- Handle connection errors and disconnections gracefully
- Provide logging for monitoring connection status
You can extend this implementation by adding features like:
- Message queuing for failed sends
- Custom authentication handling
- Heartbeat mechanism
- Connection state monitoring
- Custom retry strategies
Let me know if you need any clarification or have questions about implementing specific additional features!