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()

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.

get_sender

get_sender() -> Sender

Deprecated: use server.sender instead.

send

send(
    request: Request, client: Union[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 Union[ClientInfo, BaseSocket]

ClientInfo or BaseSocket to send to.

required

Returns:

Type Description
bool

True if the send succeeded.

broadcast

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

Broadcast a request to all connected clients.

Parameters:

Name Type Description Default
request Request

Request to broadcast.

required
except_clients Optional[list[Union[ClientInfo, BaseSocket]]]

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,
) -> Optional[Response]

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
Optional[Response]

Matching Response, or None on timeout or send failure.

ping_client

ping_client(
    client: ClientInfo, timeout: float = 5.0
) -> Optional[float]

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
Optional[float]

Latency in milliseconds, or None on timeout.

ping_client_async

ping_client_async(
    client: ClientInfo,
    callback: Callable[[Optional[float]], 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[[Optional[float]], 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_: Optional[int] = 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.SMALL). 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 to THREADING or RUST (v3.0.0) without changing any other code.

id_window int

Number of unique IDs per direction in the protocol (default: 30000). Sent to clients during the handshake. Must fit in REQUEST_ID_SIZE bytes.

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.

id_offset

Offset applied to request IDs for this client.

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: Optional[VeltixBus] = None,
    id_offset: int = 0,
) -> 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 Optional[VeltixBus]

Optional event bus for emitting client events.

None
id_offset int

Offset applied to request IDs for this client.

0

__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).

add_tag

add_tag(name: str, value: Optional[Any] = 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 Optional[Any]

The tag value (defaults to None).

None

Returns:

Type Description
bool

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

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) -> Optional[Any]

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
Optional[Any]

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.