Receive multipart messages in C with ZeroMQ
<p>I am writing a data recording system for a device that will transmit data using the ZeroMQ socket and publish multipart messages.</p>

<p>My program will need to be written in C.</p>

<p>I did manage to write a Python scripts which works exactly as it should.
This looks like this:</p>

<pre><code>import zmq
import time
import numpy as np

_HEARTBEAT_PREFIX =     b'ray.heartbeat\0'  
_RAW_DATA_PREFIX =      b'ray.rawdata\0'

context = zmq.Context.instance()

time.sleep(5)

socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.LINGER, 0)
socket.setsockopt(zmq.SUBSCRIBE, b'')
time.sleep(5)
socket.connect("tcp://localhost:50290")
time.sleep(5)
go = True
while go:

    if socket.poll(1000):

        zframes = socket.recv_multipart(flags=zmq.NOBLOCK, copy=False)

        if (zframes[0].buffer.tobytes() == _HEARTBEAT_PREFIX):
            print ('Heartbeart')
        elif (zframes[0].buffer.tobytes() == _RAW_DATA_PREFIX):
            dataToWrite = np.frombuffer(zframes[1].buffer, dtype='i2')
            print ('Raw data: ')
            # and so on ...
</code></pre>

<p>This is the first time I am working with ZMQ and trying to port this Python code to C is a real challenge. The C code I have written now will run, but does not work properly:</p>

<pre><code>#include "zhelpers.h"

int main (int argc, char *argv [])
{

  void *context   = zmq_ctx_new();
  void *subscriber = zmq_socket(context,ZMQ_SUB);

  int rc = zmq_connect(subscriber,"tcp://localhost:50290");
  assert(rc == 0);
  rc = zmq_setsockopt(subscriber,ZMQ_SUBSCRIBE, "", 0);
  assert(rc == 0); 

  while (1) 
  {
    zmq_msg_t message;
    zmq_msg_init (&amp;message);
    zmq_msg_recv (&amp;message, subscriber,0);//, ZMQ_NOBLOCK);
    //  Process the message frame


    int size = zmq_msg_size(&amp;message);
    char *string = malloc(size + 1);
    memcpy(string, zmq_msg_data(&amp;message), size);


    zmq_msg_close (&amp;message);

    string[size] = 0;
    printf("Message[%d]: %s\n", size, string);

    if (!zmq_msg_more (&amp;message))
        break;      //  Last message frame
  }
  return 0;
}
</code></pre>

<p>This code will however provide the correct size of the incoming data, but when displaying the data it shows as unreadable characters (symbols and so on..) I will need, as I do in Python, to get the incoming data as a string in order to process it further.</p>