C++11 引入豐富特性(lambda、智能指針、線程庫等),決定開發一個輕量、高並發的網絡庫 fly,替代臃腫的 ACE。
基於 JSON,格式:|長度|{type:..., cmd:..., ...}|。type+cmd 組成二級消息字。解析依賴 rapidjson。
構造參數:監聽地址、5 個回調函數(allow/init/dispatch/close/be_closed)。支持多線程 Poller/Parser,通過構造參數指定並發數。
class TestServer : public fly::base::Singleton<TestServer> {
unordered_map<uint64_t, shared_ptr<Connection>> conns;
mutex mtx;
public:
bool allow(shared_ptr<Connection> c) { return true; }
void init(shared_ptr<Connection> c) {
lock_guard<mutex> g(mtx);
conns[c->id()] = c;
LOG_INFO("connection count: %u", conns.size());
}
void dispatch(unique_ptr<Message> msg) {
LOG_INFO("recv from %s:%d: %s", msg->get_connection()->peer_addr().host.c_str(),
msg->get_connection()->peer_addr().port, msg->raw_data().c_str());
}
void close(shared_ptr<Connection> c) { /* ... */ }
void be_closed(shared_ptr<Connection> c) { /* ... */ }
void main() {
fly::init();
Logger::instance()->init(DEBUG, "server", "./log/");
auto server = make_unique<Server>(Addr("127.0.0.1", 8899),
bind(&TestServer::allow, this, _1),
bind(&TestServer::init, this, _1),
bind(&TestServer::dispatch, this, _1),
bind(&TestServer::close, this, _1),
bind(&TestServer::be_closed, this, _1));
if (server->start()) { LOG_INFO("start ok"); server->wait(); }
else LOG_ERROR("start failed");
}
};
int main() { TestServer::instance()->main(); }
類似 Server,但主動連接指定地址,回調語義相同。