89 lines
2.2 KiB
C++
89 lines
2.2 KiB
C++
|
#include <zmq.hpp>
|
|||
|
#include <iostream>
|
|||
|
#include <string>
|
|||
|
#include <list>
|
|||
|
#include <iostream>
|
|||
|
#include <fstream>
|
|||
|
#include "protobuf/user.pb.h"
|
|||
|
#include <thread> // 包含用于多线程编程的头文件
|
|||
|
#include <chrono> // 包含时间相关的头文件
|
|||
|
|
|||
|
using namespace std;
|
|||
|
static const std::string port = "5555"; //端口
|
|||
|
|
|||
|
void Publish() {
|
|||
|
zmq::context_t context(1);
|
|||
|
zmq::socket_t publisher(context, ZMQ_PUB);
|
|||
|
publisher.bind("tcp://*:5555");
|
|||
|
|
|||
|
int count = 0;
|
|||
|
while (true) {
|
|||
|
std::string message = "123456 ";
|
|||
|
message += std::to_string(count++);
|
|||
|
zmq::message_t zmqMessage(message.size());
|
|||
|
memcpy(zmqMessage.data(), message.c_str(), message.size());
|
|||
|
publisher.send(zmqMessage);
|
|||
|
|
|||
|
std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // 暂停1秒
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
|
|||
|
void Respond() {
|
|||
|
zmq::context_t context(1);
|
|||
|
zmq::socket_t socket(context, ZMQ_REP);
|
|||
|
std::string serverbind = "tcp://*:" + port;
|
|||
|
socket.bind(serverbind);
|
|||
|
|
|||
|
std::list<std::string> cacheList;
|
|||
|
|
|||
|
while (true) {
|
|||
|
zmq::message_t request;
|
|||
|
socket.recv(&request);
|
|||
|
|
|||
|
std::string message = std::string(static_cast<char*>(request.data()), request.size());
|
|||
|
std::cout << "Received request: " << message << std::endl;
|
|||
|
|
|||
|
// 模拟处理请求
|
|||
|
std::string response = "Echo: " + message;
|
|||
|
|
|||
|
zmq::message_t reply(response.size());
|
|||
|
memcpy(reply.data(), response.c_str(), response.size());
|
|||
|
|
|||
|
socket.send(reply);
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
|
|||
|
int main()
|
|||
|
{
|
|||
|
Ufgnix0802::Account account1;
|
|||
|
account1.set_id(1);
|
|||
|
account1.set_name("windsun");
|
|||
|
account1.set_password("123456");
|
|||
|
|
|||
|
string serializeToStr;
|
|||
|
account1.SerializeToString(&serializeToStr);
|
|||
|
cout << "序列化后的字节:" << serializeToStr << endl;
|
|||
|
|
|||
|
|
|||
|
Ufgnix0802::Account account2;
|
|||
|
if (!account2.ParseFromString(serializeToStr))
|
|||
|
{
|
|||
|
cerr << "failed to parse student." << endl;
|
|||
|
return -1;
|
|||
|
}
|
|||
|
cout << "反序列化:" << endl;
|
|||
|
cout << account2.id() << endl;
|
|||
|
cout << account2.name() << endl;
|
|||
|
cout << account2.password() << endl;
|
|||
|
|
|||
|
google::protobuf::ShutdownProtobufLibrary();
|
|||
|
|
|||
|
//Respond();
|
|||
|
|
|||
|
Publish();
|
|||
|
|
|||
|
return 0;
|
|||
|
}
|