Introduction

ZeroMq is a small and fast and powerful and easy to use cross platform messaging framework. It´s written in C/C++, but binding for other languages exist. There is even one for .NET - clrzmq - from one of the ZeroMq authors. However, the clrzmq binding is pretty low level. So I set out to implement a higher level abstraction of the ZeroMq functionality and add features currently missing in the clrzmq.

So, what can you do with ZeroMq through NZMQ? Here´s an example of a tiny client/server scenario:

Run this in a server process:

using(var ctx = new NzmqContext())
{
  ctx.HostService(ProcessRequests, "tcp://127.0.0.1:8000");
  Console.ReadLine();
}
...
void ProcessRequests(NzmqServiceSocket sck)
{
  while(true)
  {
    string request = sck.Receive();
    sck.Reply(request.ToUpper());
  }
}

And run this in some client process:

using(var ctx = new NzmqContext())
using(var sck = ctx.CreateClientSocket(""tcp://127.0.0.1:8000"))
{
  sck.Send("hello, world!");
  Console.WriteLine(sck.Receive());

  sck.Send("the quick brown fox jumps over the lazy dog");
  Console.WriteLine(sck.Receive());
}

That´s probably as easy as it can get for a message oriented request/response communication.

You can start client and server in any order. Receive() waits for a message/response to arrive, it´s blocking by default. But of course you can use it in a non-blocking mode and even wait for messages to arrive with a timeout.

Or check this out: a simple pub/sub communication. Here´s the server code:

using(var ctx = new NzmqContext())
using(var sck = ctx.CreatePublisherSocket("tcp://127.0.0.1:8000"))
{
  for(int i=0; i<200; i++)
  {
    sck.Broadcast("message #" + i.ToString());
    Thread.Sleep(100);
  }

  Console.ReadLine();
}

And here is the code you can start several times as a client:

using(var ctx = new NzmqContext())
using(var sck = ctx.CreateSubscriberSocket("tcp://127.0.0.1:8000"))
{
  string notification;
  while(sck.TryReceive(out notification, 3000))
    Console.WriteLine(notification);
}

The NZMQ sources provide couple of usage tests to show you, how to work with the API. But be sure to also read the ZeroMq guide although it uses C as its source language. It´s worthwhile, because if you look at the NZMQ sources you´ll see all kinds of C library calls.

NZMQ is work in progress. And if you like, contribute to it. Just let me know and I add you to the project.

Enjoy!

-Ralf Westphal
http://www.ralfw.de
http://ralfw.blogspot.com
http://geekswithblogs.com/architectsnapkin

Last edited Sep 27, 2010 at 11:24 AM by ralfw, version 8