24.2 Websocket basic usage

In GNU Artanis, a Websocket handling is triggered by setting it on a specific URL. You should use #:websocket to configure the Websocket. Here’s the API definition:

#:websocket (proto protocol-name ['inexclusive])

’inexclusive is optional. By default, each Websocket connection only servs one client. However, sometimes we do need to multicast the messages to several clients. Enable ’inexclusive is the easiest way, but it may cause the similar issue to file-description-leaking. There’re two suggestions:

Here’s a simple example for common cases:

(use-modules (artanis artanis))

(get "/echo" #:websocket '(proto echo)
     (lambda (rc)
       (:websocket rc 'payload)))

(run #:port 3000)

In this simple test, we choose the simplest echo protocol of the Websocket. This will return back the string sent from the client. Let’s also write a simple javascript function for the web frontend:

function WebSocketTest()
{
    if ("WebSocket" in window)
    {
        document.write("<p>WebSocket is supported by your Browser!</p>");

        // Let us open a web socket
        var ws = new WebSocket("ws://localhost:3000/echo");

        ws.onopen = function()
        {
            // Web Socket is connected, send data using send()
            ws.send("hello world");
            document.write("<p>Message is sent...</p>");
        };

        ws.onmessage = function (evt)
        {
            var received_msg = evt.data;
            document.write("<p>hello welcome...</p>");
        };

        ws.onclose = function()
        {
            // websocket is closed.
            document.write("<p>Connection is closed...</p>");
        };

        window.onbeforeunload = function(event) {
            socket.close();
        };
    }
    else
    {
        // Your browser doesn't support WebSockets
        document.write("<p>WebSocket NOT supported by your Browser!</p>");
    }
}