[nanomsg] When is it safe to use NN_MSG?

  • From: Stefan de Konink <stefan@xxxxxxxxx>
  • To: <nanomsg@xxxxxxxxxxxxx>
  • Date: Wed, 11 Dec 2013 03:27:55 +0100

I'm currently using a construction where an iov contains a uint32_t and a 
struct. It make sense that I have to manually set iov_len with the appropriate 
sizes of these objects.

When receiving the object back, I should receive a string-like object (instead 
of the struct). I was expecting I could use a lazy method let nanomsg do my 
allocation like in the test.

https://github.com/nanomsg/nanomsg/blob/master/tests/msg.c#L81

For some reason I cannot get the following to work, either response side 
remains 0x0 or it plainly hangs.

Sender>>
       void *msg = nn_allocmsg(result_length, 0);
       strncpy(msg, result_buf, result_length);
       iov[0].iov_base = &sd;
       iov[0].iov_len = sizeof(uint32_t);
       iov[1].iov_base = &msg;
       iov[1].iov_len = NN_MSG;
       bzero (&hdr, sizeof (hdr));
       hdr.msg_iov = iov;
       hdr.msg_iovlen = 2;
       nn_sendmsg(sock, &hdr, 0);

<<Receiver
           char *response = NULL;
           uint32_t sd;
           struct nn_msghdr hdr;
           struct nn_iovec iov [2];
           iov [0]iov_base = &sd;
           iov [0].iov_len = sizeof(uint32_t);
           iov [1].iov_base = &response;
           iov [1].iov_len = NN_MSG;
           bzero(&hdr, sizeof (hdr));
           hdr.msg_iov = iov;
           hdr.msg_iovlen = 2;
           nn_recvmsg (broker_socket, &hdr, 0);


When I change the iov[1] parts on both sides to preallocated buffers, with a 
fixed size, I do get messages around. Could someone give a hint?

Stefan
#include <nanomsg/nn.h>
#include <nanomsg/reqrep.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>

int main() {
    struct nn_msghdr hdr;
    struct nn_iovec iov[2];

    int req = nn_socket(AF_SP, NN_REQ);
    int rep = nn_socket(AF_SP, NN_REP);

    nn_bind(rep, "tcp://127.0.0.1:1234");
    nn_connect(req, "tcp://127.0.0.1:1234");

    uint32_t sd = 1;

    char *result_buf = "Hello world";
    int result_length = strlen(result_buf);

    void *msg = nn_allocmsg(result_length, 0);
    strncpy(msg, result_buf, result_length);
    iov[0].iov_base = &sd;
    iov[0].iov_len = sizeof(uint32_t);
    iov[1].iov_base = &msg;
    iov[1].iov_len = NN_MSG;
    bzero (&hdr, sizeof (hdr));
    hdr.msg_iov = iov;
    hdr.msg_iovlen = 2;
    printf("Sending...\n");
    nn_sendmsg(req, &hdr, 0);

    char *response = NULL;
    iov [0].iov_base = &sd;
    iov [0].iov_len = sizeof(uint32_t);
    iov [1].iov_base = &response;
    iov [1].iov_len = NN_MSG;
    bzero(&hdr, sizeof (hdr));
    hdr.msg_iov = iov;
    hdr.msg_iovlen = 2;

    printf("Receiving...\n");
    nn_recvmsg (rep, &hdr, 0);

    printf("Worked...\n");
    nn_sendmsg(rep, &hdr, 0);
    nn_recvmsg (req, &hdr, 0);

    printf ("%s", response);
}

Other related posts: