huang_nick
huang_nick
采纳率0%
2016-03-01 08:52 阅读 2.5k

zeromq socket网络传递结构体

1

我在服务器端发了一个结构体,在client端接收,发送应该是正常的,客户端也接到了这个数据但是一访问成员变量就segment fault,zeromq 接收到在zmq::msg_t中有个size()函数返回接收到数据的size 我比对了一下是对的上的 但是一访问成员变量就出错,觉得很奇怪,应该是会编译器以及结构体的存储有关,本人新手,求各位大神指点一二 有分

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • huang_nick huang_nick 2016-03-01 08:55

    另外 我两端的操作系统以及编译器版本都一样 应该不存在大小端的问题

    点赞 评论 复制链接分享
  • huang_nick huang_nick 2016-03-01 09:14

    附上代码 client:
    #include
    #include
    #include
    #include "../Desktop/market_handlers/src/common/zhelpers.hpp"
    using namespace std;

    struct shared {
    string a;
    string b;
    string c;
    };

    struct shared sh;

    int main ()
    {
    //Prepare our context and socket
    zmq::context_t context (1);
    zmq::socket_t socket(context, ZMQ_SUB);
    socket.setsockopt(ZMQ_SUBSCRIBE, "", 0);
    socket.connect("tcp://52.69.36.106:10014");
    while (true) {
    /*
    std::string str = s_recv(socket);
    cout << str;
    */
    string h;
    // zmq::message_t msg;
    zmq_msg_t msg;
    // socket.recv(&msg);
    while(true) {
    zmq_recv(socket, &msg, 1);

    // cout << msg.size() << "\n";
    struct shared* sha = reinterpret_cast(&msg);
    // cout << static_cast(msg.data())->a << "\n";
    cout << sha->a;
    }
    }
    return 0;
    }

    点赞 评论 复制链接分享
  • huang_nick huang_nick 2016-03-01 09:14

    server:
    #include
    #include

    #include "market_handlers/src/common/zhelpers.hpp"
    using namespace std;

    struct shared {
    string a;
    string b;
    string c;
    };

    struct shared sh;
    struct shared sh1;

    int main() {
    zmq::context_t context(1);
    zmq::socket_t socket(context, ZMQ_PUB);
    zmq_bind(socket, "tcp://*:10014");
    while (true) {
    string str;
    cin >> str;
    sh.a = str;
    cout << sh.a << "\n";
    // zmq::message_t msg(sh, sizeof(sh), NULL);
    // cout << static_cast(msg.data())->a << "\n";
    zmq_msg_t msg;
    // cout << "send? " << s_send(socket, str) << "\n";
    cout << "data ready? " << zmq_msg_init_data(&msg, &sh, sizeof(sh), NULL, NULL) << "\n";
    // cout << "data is " << static_cast(zmq_msg_data(&msg))->a << "\n";
    cout << zmq_send(socket, &msg, 1) << "\n";
    // cout << socket.send(msg, 1) << "\n";
    // cout << socket.send(msg , ZMQ_SNDMORE) << "\n";
    }
    return 0;
    }

    点赞 评论 复制链接分享

相关推荐