服务端:
#include "rpc_server.h"
using namespace rest_rpc;
using namespace rpc_service;
int main() {
rpc_server server(9980, std::thread::hardware_concurrency());
server.register_handler("publish", [&server] (rpc_conn conn, std::string key, std::string token, std::string val) {
server.publish(std::move(key), std::move(val));
});
std::string str(1024, 'A');
std::thread thd([&server, &str] {
while (true) {
server.publish("test_network_speed", str);
}
});
server.run();
return 0;
}
客户端:
#include <sys/timeb.h>
#include "rpc_client.hpp"
using namespace rest_rpc;
using namespace rpc_service;
int main(int argc, const char **argv) {
if (argc != 3) {
std::cerr << "usage:./program ip port" << std::endl;
return -1;
}
const char *ip = argv[1];
int port = atoi(argv[2]);
rpc_client client;
client.enable_auto_reconnect();
client.enable_auto_heartbeat();
bool r = client.connect(ip, port);
if (false == r) {
std::cerr << "connect to " << ip << ":" << port << "failed." << std::endl;
return -1;
}
struct stat_info {
const char *ip;
int count = 0;
long last_time = 0;
long now_time = 0;
long interval = 0;
double speed = 0;
};
stat_info info;
info.ip = ip;
info.last_time = time(nullptr);
const int M_100 = 1024 * 100;
while (true) {
client.subscribe("test_network_speed", [&info] (string_view str) {
if (++info.count >= M_100) { // 100M
info.now_time = time(nullptr);
info.interval = info.now_time - info.last_time;
info.speed = 100.0 / info.interval;
info.last_time = info.now_time;
info.count = 0;
std::cout << "from ip:" << info.ip << " to loalhost speed:" << info.speed << "M/S" << std::endl;
}
});
}
return 0;
}