WebSocket and file server How To

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.

Quick start Server Client How events are delivered The engine's own messages Serving files on the same port Connection middleware Measured limits
One server per interpreter, and its arguments are fixed at the first 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.

Quick start

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

Server

Create, start, stop

MemberAnswersDoes
Server.Create(port [, mode [, name [, rootDir]]])the serverBinds 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()boolStarts the accept loop. A missing rootDir or a port already in use is reported through OnError and answers false.
Stop()nothingStops the accept loop and unhooks the events. It does NOT reset the object, so a later Start() reuses the same port.
IsRunningboolWhether the accept loop is up.
Port, Id, Nameint, string, string?What the server was created with. Id is generated by the engine.

Events

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.

HandlerRuns 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.

Sending and inspecting

MemberDoes
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.

Client

MemberAnswersDoes
Client.Create(host, port [, timeoutMs])the clientBinds 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 resultConnects and performs the WebSocket handshake. false means it did not complete, and OnError says why.
IsConnectedboolThe live state, which is what a loop polls; it goes false when the server closes the socket.
Idstring?The id the SERVER assigned. It is null until OnId has fired.
PortintWhat Create was given.
Send(text)nothingOne text frame. A send on a closed client does nothing.
Pump()nothingRuns whatever is queued, then returns.
Wait()nothingBlocks until the client is disconnected, running the queued callbacks as they arrive.
Disconnect(), Dispose()nothingClose 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.

How events are delivered

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:

ModeMemberShape
Blocking serverserver.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 clientclient.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 blockingserver.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.
A socket pump loop ticks the engine's timers only when the run owns a window. With no window up, a 150 ms 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.

The engine's own messages

Two messages belong to the protocol itself, and both are handled for you:

MessageDirectionPurpose
__id:<id>Server to clientAssigns the client its id, which is what makes the server count it.
__ack:<id>Client to serverThe 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.

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

Serving files on the same port

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:

RequestAnswerBody
GET /hello.txt200the file (19 bytes in the probe)
GET / with no index.html404the engine's own HTML page (136 bytes)
GET / with an index.html200that page, which is what makes a folder a site
GET /nope.txt404the same page
GET /../secret.txt403the page for it (148 bytes): the path leaves the served folder, and the reason goes to the log
POST /hello.txt405the engine's page for it (161 bytes), and the reason goes to the log
A server with a 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

Connection middleware

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.

Measured limits

Each of these is how the shipped build behaves:

Demos

Three samples in assets/language/runtime, run by the engine like any other script:

FileWhat it shows
ws_chat_server.slcA chat server: ids, nicknames, broadcasts, whispers, keep-alive, and the __ protocol it invents for its clients.
ws_chat_client.slcThe matching console client: Wait() in a pump loop, and both sides of that protocol.
ws_chat_gui.slcThe 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.