Skip to content

Server

veltix.server.server.Server

TCP server for the Veltix protocol.

Accepts incoming client connections, drives the JSON raw-socket handshake, and dispatches received messages through the request handler.

Each client runs in a dedicated thread. Slow callbacks never block message reception : all user-defined handlers execute in a thread pool managed by the underlying RequestHandler.

Usage::

config = ServerConfig(host="0.0.0.0", port=8080)
server = Server(config)

def on_message(client: ClientInfo, response: Response) -> None:
    server.sender.send(Request(CHAT, b"Hello"), client=client.conn)

server.on_recv(on_message)
server.start()

is_full property

is_full: bool

Check if the server has reached its maximum connection limit.

Returns:

Type Description
bool

True if max_connection is set and all slots are taken,

bool

False otherwise.

sender property

sender: Sender

Return the sender instance for this server.

__init__

__init__(config: ServerConfig) -> None

Initialize the TCP server.

Parameters:

Name Type Description Default
config ServerConfig

Server configuration.

required

on_recv

on_recv(func: Callable) -> None

Register a callback for all received messages (before routing).

Parameters:

Name Type Description Default
func Callable

func(client: ClientInfo, response: Response)

required

on_connect

on_connect(func: Callable) -> None

Register a callback for client connections.

Parameters:

Name Type Description Default
func Callable

func(client: ClientInfo)

required

on_disconnect

on_disconnect(func: Callable) -> None

Register a callback for client disconnections.

Parameters:

Name Type Description Default
func Callable

func(client: ClientInfo)

required

route

route(type_: MessageType) -> Callable

Decorator to register a route callback for a specific message type.

Usage

@server.route(MY_TYPE) def on_my_type(client: ClientInfo, response: Response) -> None: ...

Parameters:

Name Type Description Default
type_ MessageType

Message type to intercept.

required

Returns:

Type Description
Callable

Decorator function.

send

send(request: Request, client: ClientInfo | BaseSocket) -> bool

Send a request to a client. Accepts ClientInfo or BaseSocket.

Parameters:

Name Type Description Default
request Request

Request to send.

required
client ClientInfo | BaseSocket

ClientInfo or BaseSocket to send to.

required

Returns:

Type Description
bool

True if the send succeeded.

broadcast

broadcast(request: Request, except_clients: list[ClientInfo | BaseSocket] | None = None) -> bool

Broadcast a request to all connected clients.

Parameters:

Name Type Description Default
request Request

Request to broadcast.

required
except_clients list[ClientInfo | BaseSocket] | None

Clients to exclude (ClientInfo or BaseSocket).

None

Returns:

Type Description
bool

True if all sends succeeded.

send_and_wait

send_and_wait(request: Request, client: ClientInfo, timeout: float = 5.0) -> Response | None

Send a request to a client and block until the matching response is received.

Parameters:

Name Type Description Default
request Request

Request to send.

required
client ClientInfo

Target client.

required
timeout float

Maximum time to wait for a response in seconds (default: 5.0).

5.0

Returns:

Type Description
Response | None

Matching Response, or None on timeout or send failure.

ping_client

ping_client(client: ClientInfo, timeout: float = 5.0) -> float | None

Ping a client and measure round-trip latency.

Parameters:

Name Type Description Default
client ClientInfo

Client to ping.

required
timeout float

Timeout in seconds (default: 5.0).

5.0

Returns:

Type Description
float | None

Latency in milliseconds, or None on timeout.

ping_client_async

ping_client_async(client: ClientInfo, callback: Callable[[float | None], None], timeout: float = 5.0) -> None

Ping a client asynchronously and call callback with the result.

Parameters:

Name Type Description Default
client ClientInfo

Client to ping.

required
callback Callable[[float | None], None]

Called with latency in ms, or None on timeout.

required
timeout float

Timeout in seconds (default: 5.0).

5.0

close_client

close_client(client: ClientInfo, id_: int | None = None) -> bool

Forcefully close a specific client connection.

get_clients_by_tag

get_clients_by_tag(tag: str, value: Any = None) -> list[ClientInfo]

Get all clients that have a specific tag, optionally matching a value.

Parameters:

Name Type Description Default
tag str

Tag name to filter by.

required
value Any

Optional value to match. If None, matches any value.

None

Returns:

Type Description
list[ClientInfo]

List of matching ClientInfo objects.

start

start() -> None

Start the server and begin accepting connections.

Non-blocking - starts a background thread and returns immediately.

close_all

close_all() -> None

Stop the server and close all client connections.

wait_until_closed

wait_until_closed() -> None

Block until the server is shut down via close_all() or Ctrl+C.

restart

restart() -> None

Stop the server and start it again, preserving routes and callbacks.

veltix.server.config.ServerConfig dataclass

TCP server configuration.

Attributes:

Name Type Description
host str

Server listening address (default: '0.0.0.0').

port int

Server listening port (default: 8080).

buffer_size int

Buffer size for receiving data in bytes. Use BufferSize enum for common presets (default: BufferSize.MEDIUM). Can also be set to any custom integer value.

max_connection int

Maximum number of simultaneous connections (default: -1 = unlimited).

max_message_size int

Maximum allowed message size in bytes (default: 10MB).

handshake_timeout float

Maximum time to wait for handshake completion in seconds (default: 5.0).

max_workers int

Number of worker threads for callback execution (default: 4). Increase if your on_recv callback is slow or blocking.

socket_core SocketCore

Socket implementation to use (default: ASYNC). Switch between THREADING and ASYNC without changing any other code.

id_window int

Number of unique request IDs per direction in the protocol (default: 30000). Must fit in REQUEST_ID_SIZE bytes (max 65535).

veltix.server.client_info.ClientInfo

Represents a connected client on the server side.

Holds the socket connection, address, metadata, and a thread-safe tag store. Each instance is assigned a unique auto-incrementing ID and is comparable by identity (== and hash are based on that ID).

Attributes:

Name Type Description
conn

The underlying socket connection for this client.

addr

A (host, port) tuple representing the client address.

thread_id

The identifier of the thread managing this client.

handshake_done

Whether the handshake has been completed.

tags property

tags: dict[str, Any]

Return a copy of all tags attached to this client.

Returns:

Type Description
dict[str, Any]

A dictionary of tag names to their values.

ip property

ip: str

Return the client's IP address.

Returns:

Type Description
str

The IP address as a string.

port property

port: int

Return the client's port number.

Returns:

Type Description
int

The port as an integer.

__init__

__init__(conn: BaseSocket, addr: tuple[str, int], thread_id: int, handshake_done: bool = False, bus: VeltixBus | None = None) -> None

Initialise a new ClientInfo.

Parameters:

Name Type Description Default
conn BaseSocket

The socket connection for this client.

required
addr tuple[str, int]

(host, port) tuple of the remote address.

required
thread_id int

Identifier of the thread managing this client.

required
handshake_done bool

Whether the handshake is already complete.

False
bus VeltixBus | None

Optional event bus for emitting client events.

None

__eq__

__eq__(other: object) -> bool

Check equality by unique client ID.

Parameters:

Name Type Description Default
other object

The object to compare against.

required

Returns:

Type Description
bool

True if both instances share the same client ID.

__hash__

__hash__() -> int

Return the hash based on the unique client ID.

Returns:

Type Description
int

An integer hash value.

__repr__

__repr__() -> str

Return a debug representation of the client.

Returns:

Type Description
str

A string like ClientInfo(ip='127.0.0.1', port=54321, id=3).

__setattr__

__setattr__(name: str, value: object) -> None

Block writes to attributes outside __slots__ with a guiding error.

Parameters:

Name Type Description Default
name str

The attribute name being written.

required
value object

The value being assigned.

required

__getattr__

__getattr__(name: str) -> object

Raise a guiding error when an unknown attribute is read.

Parameters:

Name Type Description Default
name str

The attribute name being read.

required

Returns:

Type Description
object

Never returns: always raises :class:AttributeError.

add_tag

add_tag(name: str, value: Any | None = None) -> bool

Add a tag to this client.

Tags are key-value pairs used for filtering and grouping clients (e.g., channel membership, role, etc.). Adding a tag that already exists will silently fail and return False.

Parameters:

Name Type Description Default
name str

The tag name.

required
value Any | None

The tag value (defaults to None).

None

Returns:

Type Description
bool

True if the tag was added, False if it already existed.

set_tag

set_tag(name: str, value: Any | None = None) -> bool

Set a tag value, creating or overwriting it.

Unlike :meth:add_tag, set_tag updates the value when the tag already exists instead of failing. It is the intended way to persist mutable tag state (e.g. a score that changes over time).

Parameters:

Name Type Description Default
name str

The tag name.

required
value Any | None

The tag value (defaults to None).

None

Returns:

Type Description
bool

Always True.

has_tag

has_tag(name: str) -> bool

Check whether this client has a specific tag.

Parameters:

Name Type Description Default
name str

The tag name to look up.

required

Returns:

Type Description
bool

True if the tag exists on this client.

has_all_tags

has_all_tags(names: list[str]) -> bool

Check whether this client has all of the given tags.

Parameters:

Name Type Description Default
names list[str]

A list of tag names to check.

required

Returns:

Type Description
bool

True if every name in names is present as a tag.

has_any_tags

has_any_tags(names: list[str]) -> bool

Check whether this client has at least one of the given tags.

Parameters:

Name Type Description Default
names list[str]

A list of tag names to check.

required

Returns:

Type Description
bool

True if at least one name in names is present as a tag.

get_tag

get_tag(name: str) -> Any | None

Return the value of a tag, or None if it does not exist.

Parameters:

Name Type Description Default
name str

The tag name to retrieve.

required

Returns:

Type Description
Any | None

The tag's value, or None if the tag is not set.

remove_tag

remove_tag(name: str) -> bool

Remove a tag from this client.

Parameters:

Name Type Description Default
name str

The tag name to remove.

required

Returns:

Type Description
bool

True if the tag was removed, False if it did not exist.

clear_tags

clear_tags() -> None

Remove all tags from this client.