为什么ZeroMQ req-rep会给我一个C ++和Python之间的空响应?

时间:2017-01-27 11:47:59

标签: python c++ zeromq

我尝试使用ZeroMQ在Python客户端和基于C ++的服务器之间架起桥梁,但我很难从服务器返回到客户端的正确响应。

Python客户端如下所示:

import zmq
import time

# Socket to talk to server
context = zmq.Context()
socket = context.socket(zmq.REQ)

socket.connect ("tcp://127.0.0.1:5563")

requestId = 0
while True:
    request = "Message %d"%requestId
    print ("Sending '%s'.. "%request)
    socket.send_string(request)

    response = socket.recv()
    print ("Response:",response)

    requestId += 1
    time.sleep(1)

C ++服务器如下所示:

zmq::context_t* context = new zmq::context_t();
zmq::socket_t* publisher = new zmq::socket_t(*context, ZMQ_REP);

unsigned int port = 5563;
std::ostringstream bindDest;
bindDest << "tcp://*:" << port;
publisher->bind(bindDest.str());

zmq::message_t request(0);

bool notInterrupted = true;
while (notInterrupted)
{
    // Wait for a new request to act upon.
    publisher->recv(&request, 0);

    // Turn the incoming message into a string
    char* requestDataBuffer = static_cast<char*>(request.data());
    std::string requestStr(requestDataBuffer, request.size());

    printf("Got request: %s\n", requestStr.c_str());

    // Call the delegate to get a response we can pass back.
    std::string responseString = requestStr + " response";
    printf("Responding with: %s\n", responseString.c_str());

    // Turn the response string into a message.
    zmq::message_t responseMsg(responseString.size());
    char* responseDataBuffer = static_cast<char*>(responseMsg.data());
    const int OffsetToCopyFrom = 0;
    responseString.copy(responseDataBuffer, responseString.size(), OffsetToCopyFrom);

    // Pass back our response.
    publisher->send(&responseMsg, 0);
}

运行时,客户报告:

  

发送消息0&#39; ..

服务器报告:

  

收到请求:消息0

     

回复:消息0响应

但是python收到一条空白消息:

  

回复:b&#39;&#39;

如果我用如下的Python实现替换C ++版本,它按预期工作:

import zmq

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

socket.bind ("tcp://127.0.0.1:5563")

replyId = 0
while True:
    request = socket.recv_string()
    print("Received: "+request)

    response = request+" response %d"%replyId
    print ("Sending response: "+response)
    socket.send_string(response)
    replyId += 1

我在C ++版本中做错了什么?

更新 - 已检查的版本...

阅读其他人的问题,人们提出的一件事是不同的版本有时会引起问题。我仔细检查过,Python正在使用v4.1.6,而C ++则在v4.0.4上。

我在这里使用C ++预建库:http://zeromq.org/distro:microsoft-windows所以我想这可能是原因?我做了一个类似的设置,从C ++发布到Python,并且运行正常,但可能在Req-Rep区域中的某些内容发生了变化。

Update2 - 它似乎不是版本......

经过大量的黑客攻击后,我终于设法获得v4.1.6来构建服务器的C ++版本,我仍然得到相同的空信息。

1 个答案:

答案 0 :(得分:1)

您需要发送缓冲区,而不是指针。

publisher->send(responseMsg, 0);

在我测试你的代码时做了这个伎俩。

希望这有帮助, 哈努哈利