libhv

repository·master·Indexed 27 days ago

https://github.com/ithewei/libhv

A high-performance, cross-platform event-loop library providing non-blocking IO, timers, and support for TCP, UDP, HTTP, WebSocket, MQTT, and Redis. It features C-style APIs (hloop, hdns, hbase, hlog) and high-level C++ classes. The library includes the evpp header-only module for C++ wrappers and wepoll, which implements the Linux epoll API for Windows Vista and higher.

Tokens
22.2K
Snippets
38
Records
123
Agent score
92%

What's inside libhv

  1. Overview of libhv

    master
    libhv is a cross-platform network library similar to libevent, libev, and libuv. It provides easy-to-use interfaces and supports a wide range of protocols. It is designed for high performance and works across Linux, Windows, macOS, Android, iOS, BSD, and Solaris.
  2. Overview of libhv HTTP module structure

    master

    The libhv HTTP module is organized into client-side components, server-side components, and core parsing logic.

    Client Components

    • HttpClient.h: Public header for the HTTP client.
    • requests.h: Provides an API mimicking the Python requests library.
    • axios.h: Provides an API mimicking the Node.js axios library.

    Server Components

    • HttpServer.h: Public header for the HTTP server.
    • HttpHandler.h: Class for handling HTTP requests.
    • HttpService.h: High-level business services, including API services, web services, and indexof services.
    • http_page.h: Utilities for constructing HTTP pages.
    • FileCache.h: File caching functionality.

    Core Parsing and Definitions

    • httpdef.h: Core HTTP definitions.
    • HttpMessage.h: Classes representing HTTP requests and responses.
    • http_content.h: HTTP Content-Type definitions.
    • HttpParser.h, Http1Parser.h, Http2Parser.h: Base and specific classes for HTTP/1.1 and HTTP/2 parsing.
    • multipart_parser.h: Parser for multipart data.
  3. Explore libhv C++ Interfaces

    master

    libhv provides high-level C++ classes for various networking protocols and services. Available classes include:

    • Core: EventLoop, Channel
    • TCP: TcpServer, TcpClient
    • UDP: UdpServer, UdpClient
    • HTTP: HttpServer, HttpClient
    • WebSocket: WebSocketServer, WebSocketClient
    • Redis: RedisClient
  4. Use libhv Base Utilities

    master

    libhv provides a wide range of low-level base utilities for system interaction, memory management, and string manipulation. Key headers include:

    • hplatform.h: OS and architecture detection (e.g., OS_WIN, OS_UNIX, ARCH_X64).
    • hdef.h: Common macros and helper functions (e.g., MAX, MIN, SAFE_FREE, IS_ALPHA).
    • hbase.h: Memory management (hv_malloc, hv_calloc) and string utilities (hv_strcontains, hv_strstartswith, hv_mkdir_p).
    • hstring.h: High-level string operations (split, replace, trim, to_string).
    • htime.h: Time and date management (gettick_ms, datetime_now, cron_next_timeout).
    • hthread.h & hmutex.h: Threading and synchronization primitives (hthread_create, hmutex_lock, hv::MutexLock, hv::RWLock).
  5. Key features of libhv

    master

    libhv provides several high-performance networking capabilities:

    • Event Loop: High-performance event loop supporting network IO, timers, idle events, custom events, and signals.
    • TCP/UDP: Supports server, client, and proxy modes. TCP includes heartbeats, reconnection, forwarding, and thread-safe write and close operations. Includes built-in packet splitting modes (fixed length, delimiter, and header length field).
    • Reliable UDP: Supported via WITH_KCP.
    • Security: SSL/TLS encryption support (via WITH_OPENSSL, WITH_GNUTLS, or WITH_MBEDTLS).
    • HTTP: Supports server/client modes with HTTPS, HTTP/1.x, HTTP/2, and gRPC. Features include static file serving, directory listing, forward/reverse proxy, sync/async API handlers, RESTful routing, middleware, keep-alive, chunked encoding, and SSE.
    • Other Protocols: WebSocket (server/client), MQTT client, and Redis client.
  6. Explore libhv C Interfaces

    master

    libhv provides a set of C-style APIs for core networking and system tasks. Key modules include:

    • hloop: Event loop management.
    • hdns: Asynchronous DNS resolution.
    • hbase: Basic utility functions.
    • hlog: Logging capabilities.
  7. Explore evpp module components and classes

    master

    The evpp module consists of the following header-only components for network programming:

    • Buffer.h: Buffer management class.
    • Channel.h: Channel class, encapsulates hio_t.
    • Event.h: Event class, encapsulates hevent_t and htimer_t.
    • EventLoop.h: Event loop class, encapsulates hloop_t.
    • EventLoopThread.h: Event loop thread class, combines EventLoop and thread.
    • EventLoopThreadPool.h: Event loop thread pool class, combines EventLoop and ThreadPool.
    • TcpClient.h: TCP client class.
    • TcpServer.h: TCP server class.
    • UdpClient.h: UDP client class.
    • UdpServer.h: UDP server class.
  8. Enable and Build Redis Support

    master

    Redis support is disabled by default. To enable it, use the --with-redis flag during configuration or -DWITH_REDIS=ON when using CMake. The Redis C++ module is located in the redis/ directory.

    ### Using Makefile
    ```shell
    ./configure --with-redis
    make

    Using CMake

    cmake -S . -B build -DWITH_EVPP=ON -DWITH_REDIS=ON -DBUILD_UNITTEST=ON
    cmake --build build --target redis_protocol_test redis_async_client_test redis_client_test redis_batch_test redis_subscriber_test
  9. Use the evpp module as a header-only library

    master
    The evpp module is designed to be header-only and does not participate in the compilation process. It provides C++ wrappers for C interfaces (such as hloop.h), drawing inspiration from muduo and evpp. You can directly include these headers in your project and modify the classes to suit your specific business logic.
  10. Use hdns for asynchronous DNS resolution

    master

    The hdns module provides a native, non-blocking DNS resolver that runs entirely within the hloop event loop. Unlike the standard blocking getaddrinfo(), hdns uses non-blocking UDP to construct and parse DNS packets, ensuring that network latency or DNS unavailability does not stall the event loop. It supports IPv4 (A), IPv6 (AAAA), and both, and automatically handles system nameservers (e.g., /etc/resolv.conf on Unix) or falls back to 8.8.8.8.

    #include "hloop.h"
    #include "hdns.h"
    #include "hsocket.h"
    
    static void on_resolved(hdns_t* query, const hdns_result_t* result, void* userdata) {
        if (result->status == HDNS_STATUS_OK) {
            // Process result->addrs
        }
    }
    
    // Inside your loop logic:
    hdns_resolve(loop, "example.com", on_resolved, userdata);
  11. Implement a WebSocket server with WebSocketServer and WebSocketService

    master

    To create a WebSocket server, inherit from or use the WebSocketServer class (which extends HttpServer) and register a WebSocketService object. The WebSocketService struct allows you to define callbacks for connection lifecycle events and message handling.

    Key components of WebSocketService:

    • onopen: Callback triggered when a WebSocket connection is opened. Receives the WebSocketChannelPtr and the initial HttpRequestPtr.
    • onmessage: Callback triggered when a message is received. Receives the WebSocketChannelPtr and the message content as a std::string.
    • onclose: Callback triggered when a connection is closed. Receives the WebSocketChannelPtr.
    • ping_interval: An integer setting the heartbeat interval.
  12. Explore libhv C and C++ examples

    master

    libhv provides a wide range of examples for both C and C++ to demonstrate its capabilities.

    C Examples include:

    • Network primitives: hloop_test.c, htimer_test.c, pipe_test.c
    • TCP/UDP: tcp_echo_server.c, tcp_chat_server.c, tcp_proxy_server.c, udp_echo_server.c, udp_proxy_server.c
    • Proxies: socks5_proxy_server.c, tinyproxyd.c
    • Protocols: jsonrpc, mqtt
    • Multi-threading patterns: multi-acceptor-processes.c, multi-acceptor-threads.c, one-acceptor-multi-workers.c

    C++ Examples include:

    • Event Loop (evpp): EventLoop_test.cpp, EventLoopThread_test.cpp, EventLoopThreadPool_test.cpp
    • Network Clients/Servers: TcpServer_test.cpp, TcpClient_test.cpp, UdpServer_test.cpp, UdpClient_test.cpp
    • HTTP/WebSocket: http_server_test.cpp, http_client_test.cpp, websocket_server_test.cpp, websocket_client_test.cpp
    • Redis: redis_client_test.cpp, redis_subscriber_test.cpp
    • RPC: protorpc

    Command Line Tool Simulations: libhv also includes implementations that simulate well-known tools like nc, nmap, httpd, wrk, curl, wget, consul, and kcptun.