Two namespaces, Server and Client, are a WebSocket server and a WebSocket client written in the engine itself. The server can also answer plain HTTP GET from a folder you name, which makes it a static file server as well, and it runs the same tcp.Use connection middleware the rest of the engine does.
Where a behaviour is a limit rather than a feature it is stated as one, so that nothing here has to be discovered twice.
Create. A second Server.Create hands back the FIRST server and ignores the arguments it was given (Create(9702, "local", "two") after Create(9701, "local", "one") answers the same object, still on port 9701 and still named one). Two servers therefore need two processes, or two interpreters.A server and a client in one script, both pumped by the same loop. This is the smallest complete round trip: the client is given an id by the server, sends a line, and gets the echo back.
var port = 9300;
var svr = Server.Create(port, "local", "probe");
svr.OnConnect((string id) => { print("connect " + id); });
svr.OnMessage((string id, string msg) => { svr.Send(id, "echo:" + msg); });
svr.Start();
var cli = Client.Create("127.0.0.1", port, 4000);
cli.OnId((string id) => { print("my id is " + id); });
cli.OnMessage((string msg) => { print("got " + msg); });
cli.Connect();
cli.Send("hello");
while (true) { svr.Pump(); cli.Pump(); Application.DoEvents(); sleep(50); }
What that prints on the shipped build: the server's connect line with the id it assigned, the client's my id is line with the same id, and got echo:hello. The Application.DoEvents() is not for the sockets: it is there so the engine's own timers and windows keep running, because a socket pump loop does not dispatch them (see How events are delivered).
| Member | Answers | Does |
|---|---|---|
Server.Create(port [, mode [, name [, rootDir]]]) | the server | Binds the details and returns the interpreter's one server. mode is "local" (default, listens on the loopback address only) or "external" (listens on every interface). name is a label a script can read back. rootDir turns on the file server, see below. |
Start() | bool | Starts the accept loop. A missing rootDir or a port already in use is reported through OnError and answers false. |
Stop() | nothing | Stops the accept loop and unhooks the events. It does NOT reset the object, so a later Start() reuses the same port. |
IsRunning | bool | Whether the accept loop is up. |
Port, Id, Name | int, string, string? | What the server was created with. Id is generated by the engine. |
Register them before Start(): the accept loop runs on its own threads and only QUEUES what it sees, so a handler registered later still receives what arrives after it, but anything that arrived first has nobody to answer.
| Handler | Runs when |
|---|---|
OnPending((string id) => { ... }) | A client finished the WebSocket handshake and has its id, but has not acknowledged it yet. |
OnConnect((string id) => { ... }) | The client acknowledged its id, which is the point where the server counts it. This is the one to use. |
OnMessage((string id, string msg) => { ... }) | A text message arrived from that client. |
OnDisconnect((string id) => { ... }) | That client is gone, closed or kicked. |
OnError((string who, string err) => { ... }) | A listener or connection failure. who is the server or the client id, err is the engine's message. |
| Member | Does |
|---|---|
Send(id, text) | Sends one text frame to that client. An unknown id is ignored, not reported. |
Broadcast(text [, excludeId]) | Sends to every known client, optionally except one (the usual echo-to-everyone-but-the-sender). |
Clients() | The registry as a dictionary, id to entry. |
ClientCount() | How many clients have ACKNOWLEDGED, i.e. what OnConnect counted. |
ClientStatus(id) | "Pending", "Acknowledged", "Disconnected", or null for an id the server does not know. A null id is refused rather than answered: read client.Id only after OnId has fired. |
ClientKick(id) | Closes that client's stream. The rest of the teardown is the ordinary disconnect path, so the entry stays in Clients() until OnDisconnect has been dispatched (ClientCount() still reads 2 right after a kick). |
Remove(id) | Forgets that registry entry now. It answers nothing to a script. |
| Member | Answers | Does |
|---|---|---|
Client.Create(host, port [, timeoutMs]) | the client | Binds the connection details. timeoutMs defaults to 15000. Idempotent per interpreter, like Server.Create: a second call answers the first client and ignores its arguments, so a script has ONE client and reconnects with Disconnect() then Connect(). |
Connect() | bool: the handshake's result | Connects and performs the WebSocket handshake. false means it did not complete, and OnError says why. |
IsConnected | bool | The live state, which is what a loop polls; it goes false when the server closes the socket. |
Id | string? | The id the SERVER assigned. It is null until OnId has fired. |
Port | int | What Create was given. |
Send(text) | nothing | One text frame. A send on a closed client does nothing. |
Pump() | nothing | Runs whatever is queued, then returns. |
Wait() | nothing | Blocks until the client is disconnected, running the queued callbacks as they arrive. |
Disconnect(), Dispose() | nothing | Close the socket. Dispose is Disconnect plus "do not wait for a finalizer", so it is what a using block reaches. |
OnId((string id) => { ... }) | The server assigned this client its id. | |
OnMessage((string msg) => { ... }) | A text message arrived. | |
OnDisconnect(() => { ... }) | The connection ended. | |
OnError((string err) => { ... }) | A transport failure, as the engine's message. |
Connect() answers the WebSocket handshake's result. true means the socket opened AND the upgrade completed, which is why a refused port, a timeout or a server that answers the handshake with something else all return false and report through OnError. IsConnected stays the property to poll inside a loop, and OnId firing is the moment the session is usable.The sockets run on their own threads and never call a script directly. Everything they see is queued, and a script runs the queue with one of three members. The three modes, and what each one gives a script:
| Mode | Member | Shape |
|---|---|---|
| Blocking server | server.Listen() | Loops until Stop(), running the queued callbacks. Nothing else on that thread runs, so a script that must also do work calls it on its own thread (a Events.Create() producer, feed.Start((EventSubject f, EventSubject s) => { svr.Listen(); })). An engine CreateTimer does NOT fire inside it: a timer armed to stop the server never ran, and Listen() never returned. |
| Blocking client | client.Wait() | Blocks until that client is disconnected, running the queued callbacks, which is what a command-line client ends with. With a producer thread disconnecting it after 800 ms, Wait returned after 866 ms with the message already delivered. |
| Non blocking | server.Pump(), client.Pump() | Runs what is queued and returns, which is the mode for a UI or for a script driving several things at once. |
CreateTimer fires 0 times across 500 ms of svr.Pump(); cli.Pump(); sleep(50); and 8 times in the same loop with Application.DoEvents() added, because the pump that statement boundaries and sleep use does nothing on a thread that owns no window. With a form shown, both variants tick (20 to 24 ticks per second of a 50 ms timer) and Application.DoEvents() is not needed. A UI script therefore pumps all of them in one loop, svr.Pump(); cli.Pump(); Application.DoEvents();, and a headless script adds DoEvents only when it wants timers or events to advance.Two messages belong to the protocol itself, and both are handled for you:
| Message | Direction | Purpose |
|---|---|---|
__id:<id> | Server to client | Assigns the client its id, which is what makes the server count it. |
__ack:<id> | Client to server | The client's acknowledgement of that id. The engine's client sends it automatically, and a Pending client becomes Acknowledged when it arrives. |
Anything else is an ordinary text message, so an application invents its own vocabulary.
__ name that is not in the table above is the DEMO's, not the engine's. The chat sample in assets/language/runtime defines __welcome:, __join:, __leave:, __nick:, __ping, __pong, __error:, __rename: and __timeout in its own handlers, on both sides. Copying the protocol means copying the demo's two handlers, not asking the engine for those names.Give Server.Create a folder as its fourth argument and the server answers plain HTTP GET from it: GET /file is that file under the folder, GET / or a directory path is its index.html, a path that climbs out of the folder is refused, and anything that is not a GET is refused by method.
var svr = Server.Create(8080, "external", "site", "D:/www");
svr.Start(); // serves D:/www over HTTP on port 8080
svr.Pump(); // a file request does not need the script, this only keeps errors flowing
Against a folder holding one hello.txt:
| Request | Answer | Body |
|---|---|---|
GET /hello.txt | 200 | the file (19 bytes in the probe) |
GET / with no index.html | 404 | the engine's own HTML page (136 bytes) |
GET / with an index.html | 200 | that page, which is what makes a folder a site |
GET /nope.txt | 404 | the same page |
GET /../secret.txt | 403 | the page for it (148 bytes): the path leaves the served folder, and the reason goes to the log |
POST /hello.txt | 405 | the engine's page for it (161 bytes), and the reason goes to the log |
rootDir is a file server AND a WebSocket server. The probe reads the connection's request head and lets the Sec-WebSocket-Key header decide: an upgrade goes to the handshake, anything else that opens with GET / is served from the folder. So one port can be a site and a socket endpoint at once, and a script can hold both on the same server object. Two details worth knowing: the head is read one byte at a time and handed to the handshake, so a client that sends its first frame in the same packet is not truncated, and a peer that sends a plain GET / without an upgrade is a FILE request, which is what a browser sends.The two roles in one script, which is the shape the probe makes possible:
var s = Server.Create(8080, "external", "site", "C:/www");
s.OnMessage((string id, string msg) => { s.Send(id, "echo:" + msg); });
s.Start(); // files under C:/www, and a WebSocket session, on the same port
Every accepted connection passes through tcp.Use BEFORE the engine reads a byte of it, so a handler can refuse by address or close the connection outright. The context and the two members are documented in the language reference, under tcp.Use; the short shape is:
tcp.Use((TcpContext ctx, Action next) => {
if (!ctx.RemoteAddress.StartsWith("127.0.0.1:")) { ctx.Close(); return; }
next();
});
next() lets the connection through to the server's own handling, ctx.Close() stops it and skips the rest of the chain, and ctx.RemoteAddress is the peer endpoint as host:port. The middleware belongs to the interpreter that started the server, so one registered after Start() still applies to the next connection.
Each of these is how the shipped build behaves:
Server.Create is idempotent: later arguments are ignored (port, name and rootDir all stay as the first call set them).Client.Create is idempotent too, so a script holds ONE client per interpreter: a second call answers the first one, and its host and port stay those of the first call. Reconnect with Disconnect() then Connect().Client.Connect() answers the handshake's result: false for a closed port, a timeout or a server that does not upgrade (each also reported through OnError), and IsConnected plus OnId are what a loop polls.Server.Listen(), Client.Wait() and Client.Connect() keep the run ALIVE while they wait: each pumps its own slices the way sleep does, so a form the run owns stays responsive, a CreateTimer fires (which is what lets a timer stop a Listen() loop), and a runThread event feed keeps being delivered (measured during a 715 ms Wait(): all 10 published values arrived). A handler can therefore run while the script is inside one of them, which is the contract sleep already has: keep such a handler short, and do not assume the statement after the call runs before it.ClientStatus(id) call with a null id is refused by the engine; the id exists only after OnId.ClientKick(id) closes the stream and leaves the registry entry to the ordinary disconnect path, so ClientCount() lags it by one dispatch.client.Name is a placeholder in this build: it always answers "Test". Read client.Id for the identity the server knows.Three samples in assets/language/runtime, run by the engine like any other script:
| File | What it shows |
|---|---|
ws_chat_server.slc | A chat server: ids, nicknames, broadcasts, whispers, keep-alive, and the __ protocol it invents for its clients. |
ws_chat_client.slc | The matching console client: Wait() in a pump loop, and both sides of that protocol. |
ws_chat_gui.slc | The same client with a form, which is the Pump() plus Application.DoEvents() shape. |
The language reference documents the two namespaces' members in their own entries (Server, Client, ClientStatus) beside tcp.Use, and the run-time details of a form that hosts one live in the Application entry.