KnutTCPServer

class knut.server.tcpserver.KnutTCPServer(address: str = '127.0.0.1', port: int = 8080)

Knut TCP socket server.

Handle all communication from clients and redirect requests to the APIs of the corresponding services. For each client, the request handler KnutTCPRequestHandler is instantiated in a new thread. The connection is kept open once a request is received to allow sending push notifications via TCP back to the connected client. See add_api() for more about how to add an API to the server.

The request handler reads UTF-8 encoded JSON messages terminated by a null byte b'\x00'. See The Knut Message for more details.

After adding APIs, the server can be run by serve_forever(). The request are then handled by the request handler until the server is shutdown. See the documentation for the socketserver module for details.

As an example, a KnutTCPServer is instantiated and knut.apis.Temperature is add to the server’s APIs. The server is run for one minute and using netcat as client, a request is send to the server:

from knut.apis import Temperature
from knut.server import KnutTCPServer
from knut.services.dummytemperature import DummyTemperature
import threading
import time

# add the DummyTemperature service back-end to the API
temperature = Temperature()
temperature.add_backend(DummyTemperature('Somewhere', 'dummy'))

server = KnutTCPServer(("localhost", 8080))
server.add_api(temperature)

with server:
    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.daemon = True
    server_thread.start()
    time.sleep(60)  # run for one minute

server.shutdown()

From the client, a TEMPERATURE_LIST_REQUEST is send to the API:

$ echo -ne '{"apiId": 1, "msgId": 2, "msg": {}}\0' | netcat localhost 8080
{"apiId": 1, "msgId": 258, "msg": {"dummy": {"location": "Somewhere",
    "unit": "\u00b0C", "condition": "\uf002", "temperature": 10.2}}}

The server finally responses with the API’s TEMPERATURE_LIST_RESPONSE.

Bind the server to the address on the specified port.

knut_serve_forever()

The main event loop of the server.

Warning

Must be implemented by a subclass.