【发布时间】:2017-01-28 02:18:03
【问题描述】:
我正在尝试使用 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”..
服务器报告:
收到请求:消息 0
响应:消息 0 响应
但是python收到一条空白消息:
响应:b''
如果我用如下 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++ 版本构建,但我仍然收到相同的空消息。
【问题讨论】: