danielwertheim

danielwertheim


notes from a passionate developer

Share


Sections


Tags


Disclaimer

This is a personal blog. The opinions expressed here represent my own and not those of my employer, nor current or previous. All content is published "as is", without warranty of any kind and I don't take any responsibility and can't be liable for any claims, damages or other liabilities that might be caused by the content.

NATS, What a beautiful protocol

Just had a quick glance at NATS and its protocol and I went: OMG, it's like so simple and therefore so tremendously beautiful. Why? I told you. It's simple. And I can read it. As in read it and understand it without having to read a boring specification about a binary fixed protocol format.

All posts in this series

Without any deep thoughts (so you can most certainly laugh at my hacky bits), using C#, I just put down something simple that publishes messages to a subscriber in Telnet:

Func<string, byte[]> encode = Encoding.UTF8.GetBytes;
Func<byte[], string> decode = Encoding.UTF8.GetString;

Func<Socket, byte[]> read = socket =>
{
    var buff = new byte[256];
    var r = socket.Receive(buff);

    return buff.Take(r).ToArray();
};

Action<Socket> dump = s =>
{
    var buff = read(s);
    Console.WriteLine(buff.Any()
        ? decode(buff)
        : "--nothing--");
};

Action<Socket, string> pub = (s, m) =>
    s.Send(encode($"pub foo {m.Length}\r\n{m}\r\n"));

using (var tcp = new TcpClient())
{
    tcp.Connect("demo.nats.io", 4222);

    dump(tcp.Client);

    while (true)
    {
        var msg = Console.ReadLine();
        if (string.IsNullOrWhiteSpace(msg))
            break;

        pub(tcp.Client, msg);

        dump(tcp.Client);
    }

    tcp.Close();
}

So now, if you start a telnet session and go:

telnet demo.nats.io 4222
sub foo subId123

Then take the C# code and run it in e.g. a console application, then you would be able to do this:

Simple, right? Which seems to be the characteristics of NATS. It's trying to be simple in the way that it doesn't try to support every use case found in an enterprise scenario. But, hey, I just started looking into it.

Cheers,

//Daniel

View Comments