Objects from C# to Python [2/3]

At this point, if you are not familiar with zeromq (also called zmq or 0mq), I suggest you read zguide which includes detailed explanations and samples in various languages on usage and patterns using zeromq.

Let’s start by creating a new Visual Studio console project called CSharpStringPublisher, and use the code below to publish the time on regular intervals:

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
using ZeroMQ;

namespace CSharpStringPublisher
{
    class Program
    {
        private static ZmqContext context_ = null;
        private static ZmqSocket socket_ = null;

        static void Main(string[] args)
        {
            context_ = ZmqContext.Create();
            socket_ = context_.CreateSocket(SocketType.PUB);
            socket_.Bind("tcp://127.0.0.1:5000");

            bool publish = true;
            Task.Run(() => {
                while (publish)
                {
                    string timestring = DateTime.Now.ToString("u");
                    Console.WriteLine("Sending '{0}' to subscribers", timestring);
                    socket_.Send(timestring, ASCIIEncoding.ASCII);
                    Thread.Sleep(1000);
                }
            });
            Console.ReadLine();
            publish = false;
        }
    }
}

We now have a simple publisher (SocketType.PUB) which will be able to publish byte arrays to any zeromq subscriber, regardless of the language you are subscribing with.
If you have ever used raw sockets in the past, one thing is noticeable as soon as you run this sample: you do not have to worry whether there are subscribers or not. At this point, regardless of the performance, this is in my opinion a huge gain already: focus on the data you want to send and let the framework handle the connections.

Let’s now write a very basic subscriber in Python. Open your favorite text editor to create PythonStringSubscriber.py and paste the following code:

import zmq

context = zmq.Context()
socket = context.socket(zmq.SUB)

socket.setsockopt(zmq.SUBSCRIBE, "")
socket.connect("tcp://127.0.0.1:5000")

while True:
    timestring = socket.recv_string()
    print timestring

If you now run both the CSharpStringPublisher and the PythonStringSubscriber, the subscriber will print every string received from the C# program. The interesting part is that if does not matter in which order you run the samples, if you start the subscriber before the publisher, or if you run multiple subscribers: data will just flows.

string_publish_subscribe

The code used in this post is available on the git repository.

The next part of the tutorial shows how to use Google’s protocol buffers to stream objects from C# to Python.