A proper introduction to NetMQ requires more than one post and is well beyond the format of this series of the posts. Instead, in a spirit of the series, this is an awareness raising post, to bring additional visibility to the great library.

NetMQ is a managed .NET port of ZeroMQ library. The idea of the both libraries is not to directly compete with the messaging solutions like RabbitMQ, ActiveMQ or NServiceBus, which provide rich high level feature set out of the box; but to provide a relatively low level API which allows to build complex solutions tailored to the specific business and functional needs.

Unlike the mentioned solutions, NetMQ does not include a central server or broker. NetMQ is based on a socket idea. Each side of communication require to open a socket and use it for communication. NetMQ, following ZeroMQ, supports many different type of sockets and each socket type has a unique behavior.

The simplest pair of sockets is RequestSocket/ResponseSocket. These two sockets, when connected to each other, allows to build synchronous client server communications.

Server code example

using (var responseSocket = new ResponseSocket("@tcp://*:5555"))
            {
                while (true)
                {
                    // receive a request message
                    var msg = responseSocket.ReceiveFrameString();

                    Console.WriteLine("Request received: " + msg);

                    // send a canned response
                    responseSocket.SendFrame("Response for " + msg);
                }
            }

Client code example

using (var requestSocket = new RequestSocket(">tcp://localhost:5555"))
            {
                requestSocket.SendFrame("Hello");
                var message = requestSocket.ReceiveFrameString();
                Console.WriteLine("requestSocket : Received '{0}'", message);

                Console.ReadKey();
            }

Samples demonstrate creation of the sockets for server and client and sending the request/response between the applications.

The real power of NetMQ comes from the ability to craft your own protocol using multi-frame messages and from the variety of the available sockets. They include async sockets, pub/sub sockets, in-proc sockets. These features differentiate ZeroMQ and NetMQ and allows to build very complex solutions, however they bring lots of complexity and require some learning. ZeroMQ guide may be a good start, even if you will end up using NetMQ – it helps to understand main principles and pattern.

blog comments powered by Disqus