← 返回主页

tacopie 使用指南

tacopie 是一个轻量级的 C++ 网络库,为上层应用提供底层的 TCP 连接和异步 I/O 支持。它常被用作 Redis 等应用的底层网络通信库。

📦 安装

从 GitHub 获取

git clone https://github.com/Cylix/tacopie.git
cd tacopie
mkdir build && cd build
cmake ..
cmake --build .

🚀 基础使用

TCP 客户端

#include <tacopie/tacopie>
#include <iostream>

int main() {
    // 创建 TCP 客户端
    tacopie::tcp_client client;
    
    // 连接到服务器
    client.connect("127.0.0.1", 8888, [](
        tacopie::tcp_client& client,
        const std::string& host,
        uint32_t port,
        const std::error_code& ec
    ) {
        if (ec) {
            std::cerr << "Connection failed: " << ec.message() << std::endl;
        } else {
            std::cout << "Connected to server" << std::endl;
        }
    });

    // 发送数据
    std::string msg = "Hello, Server!";
    client.write(msg.c_str(), msg.size());

    return 0;
}

TCP 服务器

#include <tacopie/tacopie>
#include <iostream>

int main() {
    // 创建 TCP 服务器
    tacopie::tcp_server server;
    
    // 启动服务器
    server.start("0.0.0.0", 8888, [](
        const std::shared_ptr<tacopie::tcp_socket>& socket
    ) {
        std::cout << "New client connected" << std::endl;
        
        // 设置回调处理接收到的数据
        socket->async_read({
            1024,
            [](tacopie::tcp_client& client, const tacopie::read_result& result) {
                if (result.success) {
                    std::string data(result.buffer.begin(), result.buffer.end());
                    std::cout << "Received: " << data << std::endl;
                }
            }
        });
    });

    std::this_thread::sleep_for(std::chrono::seconds(60));
    server.stop();
    return 0;
}
💡 提示: tacopie 专注于底层的 TCP 网络通信,提供轻量级的异步 I/O 功能,适合作为其他库的基础组件。
⚠️ 注意: tacopie 是一个较轻量级的库,功能相对简单。如果需要更完整的网络功能,可以考虑使用 Asio 等更成熟的库。

🔗 参考资料