87 lines
2.2 KiB
C++
87 lines
2.2 KiB
C++
#include <context.h>
|
|
#include <shm.h>
|
|
#include <tcp.h>
|
|
#include <unix_domain.h>
|
|
#include <zmq_ipc.h>
|
|
|
|
#include <argparse/argparse.hpp>
|
|
#include <iostream>
|
|
#include <optional>
|
|
#include <thread>
|
|
|
|
int parse_cmd_args(int argc, char** argv, std::string& communication,
|
|
std::string& method, std::string& data) {
|
|
argparse::ArgumentParser program("IPC_Interface");
|
|
|
|
program.add_argument("communication")
|
|
.help("zmq or shm or unix_domain")
|
|
.store_into(communication);
|
|
|
|
program.add_argument("method").help("send or receive").store_into(method);
|
|
|
|
program.add_argument("--data").default_value(std::string("")).nargs(1);
|
|
|
|
try {
|
|
program.parse_args(argc, argv);
|
|
} catch (const std::exception& err) {
|
|
std::cerr << err.what() << std::endl;
|
|
std::cerr << program;
|
|
return 1;
|
|
}
|
|
|
|
if (method == "send") {
|
|
std::cout << method << std::endl;
|
|
}
|
|
data = program.get<std::string>("--data");
|
|
return 0;
|
|
}
|
|
|
|
int run_main(int argc, char** argv) {
|
|
std::string communication;
|
|
std::string method;
|
|
std::string data;
|
|
|
|
if (auto res = parse_cmd_args(argc, argv, communication, method, data);
|
|
res != 0) {
|
|
return res;
|
|
}
|
|
|
|
IpcRequestReplyContext context;
|
|
|
|
// 使用共享内存策略
|
|
if (communication == "zmq") {
|
|
context.setStrategy(std::make_unique<ZMQRequestReply>());
|
|
} else if (communication == "shm") {
|
|
context.setStrategy(std::make_unique<ShmRequestReply>());
|
|
} else if (communication == "unix_domain") {
|
|
context.setStrategy(std::make_unique<UnixDomainRequestReply>());
|
|
} else if (communication == "tcp") {
|
|
context.setStrategy(std::make_unique<TcpRequestReply>());
|
|
}
|
|
|
|
if (method == "send") {
|
|
if (!data.empty()) {
|
|
auto res = context.send(data);
|
|
if (!res.has_value()) {
|
|
std::cerr << "send error: " << res.error() << std::endl;
|
|
return -1;
|
|
}
|
|
std::cout << "send success" << std::endl;
|
|
}
|
|
|
|
} else if (method == "receive") {
|
|
auto read_msg = context.receive();
|
|
if (!read_msg.has_value()) {
|
|
std::cerr << "receive error: " << read_msg.error() << std::endl;
|
|
return -1;
|
|
}
|
|
std::cout << "Received: " << *read_msg << std::endl;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
int main(int argc, char** argv) {
|
|
return run_main(argc, argv);
|
|
// return 0;
|
|
} |