如何在 C++ 中使用 ZeroMQ 发送包含数组的结构时解决错误

How to solve an Error while sending a structure containing an array using ZeroMQ in C++

客户端向服务器发送一个结构(包含一个数组)十次。服务器的工作是接收这个结构并打印它。但它只接收一次结构并打印它并退出并给出此错误
terminate called after throwing an instance of 'zmq::error_t'”。

这是客户端 C++ 代码:

#include <zmq.hpp>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <zmq2.h>
#include "structure.h"

int main (void)
{
    int flags=0,value,buffer[10];
    printf ("Connecting to hello world server…\n");
    void *context = zmq_ctx_new ();
    void *requester = zmq_socket (context, ZMQ_REQ);
    zmq_connect (requester, "tcp://localhost:5555");


    for(int i=0;i!=10;i++)
    {
        msg.arr[i]=i;   
    }

    for(int i=0;i!=10;i++)
    {
        printf ("Sending Hello %d…\n", i);
        zmq_send(requester,&msg, sizeof(Message),0);
    }
    zmq_close (requester);
    zmq_ctx_destroy (context);
    return 0;
}

这是服务器 C++ 代码:

#include <stdint.h>
#include "structure.h"
#include "zmq.hpp"
#include <string>
#include <iostream>
#include <unistd.h>

int main () {
    int val;
    zmq::context_t context (1);
    zmq::socket_t socket (context, ZMQ_REP);
    socket.bind ("tcp://*:5555");
    while(true)
    {
        Message* msg;   
        zmq::message_t zmsg;
        socket.recv(&zmsg);
        msg = (Message*)zmsg.data();
        for(int i=0;i<10;i++)
        {
            std::cout<<msg->arr[i]<<std::endl;  
        }
        sleep(1);
    }
    return 0;
}

这是structure.h

struct Message
{
  int arr[10];
}msg;

如何从服务器端接收所有十个结构并打印接收到的十个结构?

提前致谢。

最好使用 XREQ/XREP、
的 PUSH/PULL,因为原始 REP/REQ 强制执行严格的 .send()- 链。 recv()-.send()-.recv()- ...

如果您的需求与上面表达的完全一样,只需更改 ZeroMQ 可扩展正式通信原型模式就足够了。

如果您选择尽可能接近 REQ/REP "similarity",请使用 XREQ/XREP,如果有更多话要说计划进一步扩展分布式 signalling/messaging 服务基础设施,最好使用一对 PUSH/PULL[ 串联单向软管 C->S + S->C =37=] + PUSH/PULL.

A PAIR/PAIR 可能是一个选项,如果消息传递范例可以只与一个排他的节点对一起使用,其中 PAIR/PAIR(实现) 不提供稍后扩展到 .connect()N:11:MN:M 对等节点框架的方法。