首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

基於 C++11 開發高並發網絡庫:fly 架構設計與使用

     編輯:關於C++

背景

C++11 引入豐富特性(lambda、智能指針、線程庫等),決定開發一個輕量、高並發的網絡庫 fly,替代臃腫的 ACE。

架構模塊

  • base:日誌、ID 分配器、隨機數、隊列等基礎設施。
  • task:任務抽象、調度執行器。
  • net:核心網絡層,封裝 Parser(協議解析)、Acceptor(監聽)、Poller(I/O 多路複用)、Connection(連接)、Server/Client 入口類。

協議設計

基於 JSON,格式:|長度|{type:..., cmd:..., ...}|。type+cmd 組成二級消息字。解析依賴 rapidjson。

核心類:Server

構造參數:監聽地址、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(); }

Client 類

類似 Server,但主動連接指定地址,回調語義相同。

優勢

  • C++11 風格,代碼簡潔,無宏、無繁重繼承體系。
  • shared_ptr 管理連接生命周期,自動處理引用計數。
  • 回調基於 std::function/bind,靈活綁定成員函數/lambda。
  • 開源地址:github.com/lichuan/fly
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved