D alternative for node.js's socket.IO?

Neia Neutuladh neia at ikeran.org
Mon Oct 22 22:08:39 UTC 2018


On Mon, 22 Oct 2018 20:14:53 +0000, Fleel wrote:

> On Monday, 22 October 2018 at 05:36:00 UTC, Nick Sabalausky (Abscissa)
> wrote:
>> Vibe.D's existing HTTP and TCP support is perfectly sufficient,
>> and will probably also result in FAR simpler user code due to the lack
>> of necessity for callbacks
> 
> How simple is Vibe.D's method of sending messages between client and
> server? In socket.IO all I have to do is (on the sending side)
> socket.emit("testMessage", "Hi"), and on the receiving side,
> socket.on("testMessage", function(contents) {console.log(contents)}). Is
> Vibe.D as simple as this?

Not quite as simple; socket.io is a very slightly higher level API.

To replicate the server-side part of that, I'd write something like:

    void delegate(string)[string] handlers;
    router.get("/chatsocket", handleWebSockets((scope WebSocket socket)
    {
        while (true)
        {
            socket.waitForData;
            if (!socket.connected) break;
            string rawData = socket.receiveText;
            auto parts = rawData.splitter("|");
            auto topic = parts.front;
            parts.popFront;
            string payload = parts.empty ? null : parts.front;
            if (auto handler = topic in handlers)
            {
                (*handler)(payload);
            }
        }
    });
    handlers["testMessage"] = (s) => writeln(s);

In other words:

* We have a set of handlers. Each handler applies to a topic (one per 
topic) and accepts a string of data.
* When someone connects to the "/chatsocket" endpoint, set up a websocket.
* Accept text datagrams on the websocket. They have a format of "topic|
payload", or just "topic".
* If there's a handler for that topic, send the payload to that handler.
* If there's no handler, do nothing.

You also have to know that you're not supporting browsers older than five 
years.

Also, that's assuming websockets are appropriate. WebRTC might be 
preferable for your use case (and socket.io might use that? it's difficult 
to tell), and that would require a lot more work.


More information about the Digitalmars-d mailing list