只是尝试创建一个 c++ 程序,提示用户输入并根据该输入通过 ZeroMQ 向另一台服务器发送一条消息。如果您使用 Wireshark 以 ASCII 格式检查此消息,则消息应如下所示:
1.0
1616531531
userinputuserinputuserimput
但我最终得到的是:
>1.0
1616531531
userinputuserinputuserimput
我试着硬编码我的命令而不是使用终端,但我仍然得到相同的结果。 visual studio 中的调试显示在发送到 ZeroMQ 之前没有插入“>”...这是我的代码,我做错了什么或者我可以做些什么不同的事情?
#include <iostream>
#include <string>
#include <zmq.h>
int main() {
void* context = zmq_ctx_new();
void* socket = zmq_socket(context, ZMQ_PUSH);
zmq_connect(socket, "tcp://localhost:5555");
int immediate = 1;
zmq_setsockopt(socket, ZMQ_IMMEDIATE, &immediate, sizeof(immediate));
std::string api_class, api_name, argument;
std::cout << "Enter api-class: ";
std::getline(std::cin, api_class);
std::cout << "Enter api-name: ";
std::getline(std::cin, api_name);
std::cout << "Enter argument: ";
std::getline(std::cin, argument);
std::string message = "\x01\x01\x03"
"1.0"
"\x01\r\n"
"1616531531"
"\x01\r\n"
+ api_class + "\x01" + "\031" + api_name + "\x02"
+ argument;
char* buffer = new char[message.size()];
std::copy(message.begin(), message.end(), buffer);
zmq_send(socket, buffer, message.size(), 0);
zmq_msg_t response;
zmq_msg_init(&response);
int received = zmq_msg_recv(&response, socket, 0);
if (received == -1) {
std::cerr << "Failed to receive response: " << zmq_strerror(zmq_errno()) << std::endl;
}
else {
std::string response_str(static_cast<char*>(zmq_msg_data(&response)), zmq_msg_size(&response));
std::cout << "Received response: " << response_str << std::endl;
}
zmq_msg_close(&response);
zmq_close(socket);
zmq_ctx_destroy(context);
return 0;
}