Gracefully close the server when all clients disconnect:
import asyncio
import websockets
from typing import Tuple
from dpongpy.log import logger
class Server:
def init(self, port: int, num_clients: int = 2):
self.port = port
self.num_clients = num_clients
self.clients = set() # Store client WebSocket connections
self.message_queue = asyncio.Queue()
self.server = None
self.lobby_full_event = asyncio.Event()
code
def is_lobby_full(self) -> bool:
return len(self.clients) >= self.num_clients
async def start(self):
# Start the server and serve clients continuously without a loop
self.server = await websockets.serve(self.handle_client, "localhost", self.port)
print(f"Server listening on IP: localhost, Port: {self.port}")
async def handle_client(self, websocket, path):
self.clients.add(websocket)
print(f"New client connected: {websocket.remote_address}")
print(f"Waiting for {self.num_clients - len(self.clients)} more clients to join...")
if self.is_lobby_full():
self.lobby_full_event.set()
try:
await self.lobby_full_event.wait()
async for message in websocket:
await self.on_message(websocket, message)
except websockets.exceptions.ConnectionClosed:
print(f"Client disconnected: {websocket.remote_address}")
finally:
self.clients.remove(websocket)
if len(self.clients) < self.num_clients:
self.lobby_full_event.clear()
async def on_message(self, client_socket, message: str):
await self.message_queue.put((client_socket, message))
async def receive(self) -> Tuple[websockets.WebSocketServerProtocol, str]:
try:
# Try to get a message without waiting
return self.message_queue.get_nowait()
except asyncio.QueueEmpty:
logger.debug("No messages in the queue, waiting for new message...")
# Wait for the next message when the queue is empty
return await self.message_queue.get()
async def send(self, client_socket, payload: str):
if client_socket in self.clients:
await client_socket.send(payload)
else:
logger.debug(f"Client {client_socket.remote_address} not found in active clients")
async def close(self):
# Send shutdown message to all clients
for client in self.clients:
await client.send("_server_shutdown_")
await client.close()
if self.server:
self.server.close()
await self.server.wait_closed()
async def __aenter__(self):
await self.start()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.close()
Assistant
if name == "main":
server = Server(1234)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(server.start())
loop.run_forever() # Keep the loop running
finally:
loop.run_until_complete(server.close())
To gracefully close the server when all clients disconnect, you can modify the handle_client method to monitor the number of connected clients. When the last client disconnects, the server will initiate a shutdown process by closing all active connections and stopping the event loop.
Below is the updated code with the necessary modifications:
python
import asyncio
import websockets
from typing import Tuple
from dpongpy.log import logger
class Server:
def __init__(self, port: int, num_clients: int = 2):
self.port = port
self.num_clients = num_clients
self.clients = set() # Store client WebSocket connections
self.message_queue = asyncio.Queue()
self.server = None
self.lobby_full_event = asyncio.Event()
def is_lobby_full(self) -> bool:
return len(self.clients) >= self.num_clients
async def start(self):
# Start the server and serve clients continuously without a loop
self.server = await websockets.serve(self.handle_client, "localhost", self.port)
print(f"Server listening on IP: localhost, Port: {self.port}")
async def handle_client(self, websocket, path):
self.clients.add(websocket)
print(f"New client connected: {websocket.remote_address}")
print(f"Waiting for {self.num_clients - len(self.clients)} more clients to join...")
if self.is_lobby_full():
self.lobby_full_event.set()
try:
await self.lobby_full_event.wait()
async for message in websocket:
await self.on_message(websocket, message)
except websockets.exceptions.ConnectionClosed:
print(f"Client disconnected: {websocket.remote_address}")
finally:
self.clients.remove(websocket)
if len(self.clients) < self.num_clients:
self.lobby_full_event.clear()
# Check if all clients have disconnected
if len(self.clients) == 0:
print("All clients have disconnected. Shutting down the server.")
# Initiate server shutdown
await self.close()
# Stop the event loop gracefully
asyncio.get_event_loop().stop()
async def on_message(self, client_socket, message: str):
await self.message_queue.put((client_socket, message))
async def receive(self) -> Tuple[websockets.WebSocketServerProtocol, str]:
try:
# Try to get a message without waiting
return self.message_queue.get_nowait()
except asyncio.QueueEmpty:
logger.debug("No messages in the queue, waiting for new message...")
# Wait for the next message when the queue is empty
return await self.message_queue.get()
async def send(self, client_socket, payload: str):
if client_socket in self.clients:
await client_socket.send(payload)
else:
logger.debug(f"Client {client_socket.remote_address} not found in active clients")
async def close(self):
# Send shutdown message to all clients
shutdown_tasks = []
for client in self.clients.copy():
shutdown_tasks.append(client.send("_server_shutdown_"))
shutdown_tasks.append(client.close())
if shutdown_tasks:
await asyncio.gather(*shutdown_tasks, return_exceptions=True)
if self.server:
self.server.close()
await self.server.wait_closed()
print("Server has been shut down.")
async def __aenter__(self):
await self.start()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.close()
if __name__ == "__main__":
server = Server(1234)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(server.start())
loop.run_forever() # Keep the loop running
except KeyboardInterrupt:
print("Received exit signal. Shutting down...")
finally:
loop.run_until_complete(server.close())
loop.close()
Explanation of Changes
Monitoring Client Disconnections:
Inside the finally block of the handle_client method, after removing the disconnected client from the self.clients set, we check if the set is empty (len(self.clients) == 0).
If all clients have disconnected, the server initiates the shutdown process by calling await self.close() and then stops the event loop gracefully using asyncio.get_event_loop().stop().
Graceful Shutdown in close Method:
The close method now ensures that all active clients receive a shutdown message ("_server_shutdown_") before their connections are closed.
It uses asyncio.gather with return_exceptions=True to handle any exceptions that might occur during the shutdown process without interrupting the shutdown sequence.
After notifying all clients, the server itself is closed using self.server.close() followed by await self.server.wait_closed() to ensure that all server resources are properly released.
A confirmation message "Server has been shut down." is printed to indicate that the shutdown process is complete.
Handling Event Loop in __main__:
The __main__ block now includes a try-except-finally structure to handle graceful shutdowns triggered by user interruptions (like pressing Ctrl+C).
Upon receiving an interrupt (KeyboardInterrupt), the server prints a message and proceeds to call server.close() to ensure all resources are cleaned up properly.
Finally, loop.close() is called to close the event loop.
Additional Recommendations
Exception Handling: Ensure that all potential exceptions are appropriately handled to prevent the server from crashing unexpectedly. The use of return_exceptions=True in asyncio.gather helps in managing exceptions during the shutdown process.
Resource Cleanup: Always ensure that all resources (like open sockets) are properly closed to prevent resource leaks. The updated close method takes care of this by closing all client connections and the server itself.
Logging: Consider using a more robust logging mechanism instead of print statements for better monitoring and debugging in production environments.
With these modifications, your server will now gracefully shut down once all connected clients disconnect, ensuring a clean and orderly termination of all server activities.