Overview
The Server class manages multiple client connections, creating a Channel instance for each one. It can run in the main thread or in a background daemon thread for host/client P2P setups.
Class Definition
A generic async TCP server parameterized by the Channel type.
Class Attributes
The Channel subclass instantiated for each new connection. Must be set in your subclass.
Hostname or IP address the server is bound to.
Port number the server is listening on.
List of currently connected client channels.
Constructor
def __init__(
self,
host: str = "127.0.0.1",
port: int = 5071,
) -> None
Initialize the server.
Hostname or IP to bind to. Use "0.0.0.0" for all interfaces.
Port number to listen on.
Properties
address
@property
def address(self) -> tuple[str, int]
Server bind address as a (host, port) tuple.
A tuple containing the host and port the server is bound to.
Methods
start
async def start(self) -> None
Start accepting connections. Binds to host:port and begins listening for incoming TCP connections.
This is an async method that must be awaited.
run
async def run(self) -> None
Run the server forever. Blocks until the server is stopped or the task is cancelled.
This is an async method that must be awaited.
launch
Start the server and block forever. Convenience wrapper that hides asyncio boilerplate. Equivalent to calling start() then run() inside asyncio.run(). Handles KeyboardInterrupt gracefully.
Example:
GameServer(host="0.0.0.0", port=5071).launch()
stop
async def stop(self) -> None
Stop the server and disconnect all clients.
This is an async method that must be awaited.
start_background
def start_background(self) -> threading.Thread
Start the server in a daemon background thread. Useful for Host Game scenarios where the main thread needs to remain free for the game loop or UI.
The thread running the server.
on_connect
def on_connect(self, channel: C, addr: tuple[str, int]) -> None
Called when a new client connects. Override to run per-client setup (e.g. add to a player list).
The newly created channel for this client.
(host, port) of the remote client.
on_disconnect
def on_disconnect(self, channel: C) -> None
Called when a client disconnects. Override to run per-client cleanup.
The channel that disconnected.
send_to_all
def send_to_all(self, data: dict[str, Any]) -> None
Broadcast a message to every connected client.
Message dictionary to send to all channels.
Complete Example
from repod import Server, Channel
class GameChannel(Channel):
def Network_chat(self, data: dict) -> None:
self.server.send_to_all(
{"action": "chat", "text": data["text"]}
)
class GameServer(Server):
channel_class = GameChannel
GameServer(host="0.0.0.0", port=5071).launch()