Creating a server#

Instantiating the server class#

You can instantiate the server class with socketsc.SocketServer. It takes 3 parameters:

address

A tuple with the address and port to bind to

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 server
server = socketsc.SocketServer(("localhost", 8080), socketsc.AF_INET, socketsc.SOCK_TCP)

Registering an event#

You can register an event through the socketsc.SocketServer.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_question(client: socketsc.ServerSocketWrapper, data):
    # Callback function for the "question" event
    client.emit("answer", "Hello client")


# Register an event
server.on("question", on_question)

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

on_event(client, data)

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

Parameters

Starting the server#

Now that we have registered our event, we can start the server with the socketsc.SocketServer.serve method.

print("Server listening on port 8080")
# Starting the server
server.serve()

The server will now listen for incoming connections and execute the callback function when the events are triggered.

Full code#

import socketsc

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


def on_question(client: socketsc.ServerSocketWrapper, data):
    # Callback function for the "question" event
    client.emit("answer", "Hello client")


# Register an event
server.on("question", on_question)

print("Server listening on port 8080")
# Starting the server
server.serve()

Learn more#