Creating a client#

Instantiating the client class#

Just like the server you can instantiate the client class with socketsc.SocketClient. It takes 3 parameters:

address

A tuple with the address and port of the server

address_family

The address family to use, socketsc.AF_INET or socketsc.AF_INET6

sock_type

The socket type to use, socketsc.SOCK_TCP, UDP not supported yet

import socketsc

# Instantiate the client
server = socketsc.SocketClient(("localhost", 8080), socketsc.AF_INET, socketsc.SOCK_TCP)

Registering an event#

You can register an event through the socketsc.SocketClient.on method. It takes 2 parameters:

event_name

The name of the event to register

event_exec

The function to execute when the event is triggered

def on_answer(conn: socketsc.SocketClient, answer):
    # Callback function for the "answer" event
    print(f"Server answered: {answer}")


# Register an event
server.on("answer", on_answer)

The function that you pass to the socketsc.SocketClient.on method will be called like this:

on_event(client, data)

The callback function that will be executed when the event is triggered.

Parameters

Emitting an event#

You can emit an event through the socketsc.SocketClient.emit method. It takes 2 parameters:

event_name

The name of the event to emit

data

The data to send to the server. Accepts any json serializable data and bytes.

# Emit the event with the data
server.emit("question", "Are you there server?")

Full code#

import socketsc

# Instantiate the client
server = socketsc.SocketClient(("localhost", 8080), socketsc.AF_INET, socketsc.SOCK_TCP)


def on_answer(conn: socketsc.SocketClient, answer):
    # Callback function for the "answer" event
    print(f"Server answered: {answer}")


# Register an event
server.on("answer", on_answer)

# Emit the event with the data
server.emit("question", "Are you there server?")

Learn more#

Check out how to remove an event in the next section.