### Perform HTTP GET Request in C++ Source: https://context7.com/acl-dev/demo/llms.txt Demonstrates how to perform an HTTP GET request using the ACL library, including setting query parameters and retrieving the response body. The code shows both a detailed header setup and a simpler URL-based request. Requires including ``. ```cpp #include int main(void) { acl::http_request req("www.baidu.com:80"); acl::http_header& hdr = req.request_header(); hdr.set_url("/s") .set_host("www.baidu.com") .add_param("ie", "utf-8") .add_int("f", 8) .add_int("rsv_bp", 1) .add_param("tn", "monline_4_dg") .add_param("wd", "freebsd"); if (!req.request(NULL, 0)) { printf("request error!\r\n"); return 1; } acl::string body; if (!req.get_body(body)) { printf("get_body error!\r\n"); return 1; } printf("%s\r\n", body.c_str()); // Alternative: simpler URL format acl::http_request req2("http://www.baidu.com"); if (!req2.request(NULL, 0)) { printf("request error\r\n"); return 1; } body.clear(); if (!req2.get_body(body)) { printf("get_body error\r\n"); return 1; } printf("ok: %s\r\n", body.c_str()); return 0; } ``` -------------------------------- ### Parameterized MySQL Queries with C++ Source: https://context7.com/acl-dev/demo/llms.txt Demonstrates executing parameterized SQL queries using prepared statements with the ACL MySQL connector. This includes examples of SELECT, INSERT, UPDATE, and DELETE operations, ensuring secure and efficient database interactions. ```cpp #include static void tbl_select(acl::db_handle& db) { const char* username = "user1"; acl::query query; query.create_sql("select nick from user_tbl where user=:user") .set_parameter("user", username); if (db.exec_select(query) == false) { printf("sql(%s) error\r\n", query.to_string().c_str()); return; } for (size_t i = 0; i < db.length(); i++) { const acl::db_row* row = db[i]; const char* nick = (*row)["nick"]; printf("user(%s)'s nick is %s\r\n", username, nick ? nick : "null"); } } static void tbl_delete(acl::db_handle& db) { const char* username = "user1"; acl::query query; query.create_sql("delete from user_tbl where user=:user") .set_parameter("user", username); if (db.exec_update(query) == false) printf("sql(%s) error\r\n", query.to_string().c_str()); else printf("delete %s ok\r\n", username); } int main(void) { acl::acl_cpp_init(); acl::log::stdout_open(true); const char* libpath = "./libmysqlclient_r.so"; acl::db_handle::set_loadpath(libpath); const char* dbaddr = "127.0.0.1:3306", *dbname = "acl_db", *dbuser = "db_user", *dbpass = "111111"; int dblimit = 10; acl::mysql_conf dbconf(dbaddr, dbname); dbconf.set_dbuser(dbuser).set_dbpass(dbpass).set_dblimit(dblimit); acl::mysql_handle db(dbconf); tbl_select(db); tbl_delete(db); return 0; } ``` -------------------------------- ### Install ACL RPM on Ubuntu or CentOS-32 Source: https://github.com/acl-dev/demo/blob/master/COMPILE.md Commands to build and install the ACL RPM package on Ubuntu or 32-bit CentOS systems. This involves navigating to the ACL directory and using `make` followed by `make packinstall`. ```shell #cd acl; make #make packinstall ``` -------------------------------- ### Redis Pipeline Operations with Multi-threading in C++ Source: https://context7.com/acl-dev/demo/llms.txt This C++ code demonstrates how to leverage Redis pipeline mode for batch operations. It utilizes multi-threading to maximize throughput and minimize latency by sending multiple commands to Redis without waiting for individual responses. The example includes setting, getting, and deleting keys within a pipeline, managed by a custom `redis_thread` class and a main function to orchestrate multiple threads. ```cpp #include class redis_thread : public acl::thread { public: redis_thread(acl::redis_client_pipeline& pipeline) : pipeline_(pipeline) {} ~redis_thread(void) {} protected: void* run(void) { acl::string key, value; acl::redis cmd(&pipeline_); cmd.set_pipeline(&pipeline_); for (int i = 0; i < 10000; i++) { key.format("key-%lu-%d", acl::thread::self(), i); value.format("val-%lu-%d", acl::thread::self(), i); if (!cmd.set(key, value)) { printf("set %s error, %s\r\n", key.c_str(), cmd.result_error()); break; } if (!cmd.get(key, value)) { printf("get %s error, %s\r\n", key.c_str(), cmd.result_error()); break; } if (cmd.del(key) < 0) { printf("del %s error: %s\r\n", key.c_str(), cmd.result_error()); break; } cmd.clear(); } return NULL; } private: acl::redis_client_pipeline& pipeline_; }; int main(void) { acl::redis_client_pipeline pipeline("10.110.28.210:9001"); pipeline.set_password("Wabjtam123"); pipeline.start_thread(); std::vector threads; for (int i = 0; i < 100; i++) { acl::thread* thr = new redis_thread(pipeline); threads.push_back(thr); thr->start(); } for (std::vector::iterator it = threads.begin(); it != threads.end(); ++it) { (*it)->wait(); delete *it; } pipeline.stop_thread(); return 0; } ``` -------------------------------- ### Install ACL RPM on CentOS-64 Source: https://github.com/acl-dev/demo/blob/master/COMPILE.md Commands to build and install the ACL RPM package on a 64-bit CentOS system. This involves navigating to the packaging directory and using `make` followed by `rpm -ivh`. ```shell #cd acl/packaging; make #cd acl/packaging/x86_64; rpm -ivh acl-libs-*.rpm ``` -------------------------------- ### C++11 NIO HTTP Server with Fiber Pool Source: https://context7.com/acl-dev/demo/llms.txt This C++11 code implements an HTTP server using non-blocking I/O and a fiber pool. It defines an http_servlet class to handle requests and a server_run function to manage client connections. The main function initializes the fiber pool and starts the server, demonstrating efficient concurrency for network applications. ```cpp #include #include #include #include #include class http_servlet : public acl::HttpServlet { public: http_servlet(acl::socket_stream* conn) : HttpServlet(conn, (acl::session*) nullptr) {} ~http_servlet() override = default; bool doGet(acl::HttpServletRequest& req, acl::HttpServletResponse& res) override { const char data[] = "hello world!\r\n"; res.setContentLength(sizeof(data) - 1); res.setKeepAlive(req.isKeepAlive()); return res.write(data, sizeof(data) - 1) && req.isKeepAlive(); } }; static void handle_client(acl::fiber_pool& fibers, nio::client_socket* client) { auto* conn = new acl::socket_stream; conn->open(client->sock_handle()); auto* serv = new http_servlet(conn); (*client).on_read([&fibers, client, serv](nio::socket_t fd, bool expired) { if (expired) { printf("Read timeout from fd %d\r\n", fd); client->close_await(); return; } client->read_disable(); fibers.exec([client, serv] { if (serv->doRun()) { client->read_await(5000); } else { client->close_await(); } }); }).on_error([client](nio::socket_t) { client->close_await(); }).on_close([client, conn, serv](nio::socket_t fd) { printf("Closing client fd %d\r\n", fd); conn->unbind_sock(); delete conn; delete serv; delete client; return true; }); client->read_await(5000); } static void server_run(acl::fiber_pool& fibers, nio::nio_event& ev, const char* ip, int port) { nio::server_socket server; if (!server.open(ip, port)) { printf("Listen error, addr: %s:%d\r\n", ip, port); return; } printf("Listen %s:%d ok\r\n", ip, port); server.set_on_accept([&fibers, &ev] (nio::socket_t fd, const std::string& addr) { printf("Accept one client from %s, fd: %d\r\n", addr.c_str(), fd); auto* client = new nio::client_socket(ev, fd); handle_client(fibers, client); }).set_on_error([]() { printf("Accept error\r\n"); }).set_on_close([]() { printf("server socket closed\r\n"); }); server.accept_await(ev); while (true) { ev.wait(1000); } } int main(int argc, char *argv[]) { const char* ip = "127.0.0.1"; int port = 8288; std::shared_ptr fibers (new acl::fiber_pool(10, 100, -1, 500, 32000, false)); go[fibers] { while (true) { acl::fiber::delay(1000); printf("box_min: %zd, box_max: %zd, box_count: %zd, box_idle: %zd\r\n", fibers->get_box_min(), fibers->get_box_max(), fibers->get_box_count(), fibers->get_box_idle()); } }; go[fibers, ip, port] { nio::nio_event ev(102400, nio::NIO_EVENT_T_KERNEL, nio::NIO_EVENT_F_DIRECT); server_run(*fibers, ev, ip, port); }; acl::fiber::share_epoll(true); acl::fiber::schedule(); return 0; } ``` -------------------------------- ### Programmatic JSON Building with ACL++ in C++ Source: https://context7.com/acl-dev/demo/llms.txt This C++ code showcases the ACL++ library's fluent API for building JSON documents programmatically. It demonstrates creating complex data structures including arrays and objects. The examples illustrate different ways to add elements and structure the JSON output, which is then serialized to a string. ```cpp #include #include #include static void test_build1() { acl::json json; acl::json_node& root = json.get_root(); acl::json_node& a = root.add_array(true); a.add_child(false, true).add_text("name", "zsx"); a.add_child(false, true).add_number("age", 100); a.add_child(false, true).add_bool("man", true); acl::string buf; json.to_string(&buf); printf("%s\r\n", buf.c_str()); } static void test_build2() { acl::json json; acl::json_node& root = json.get_root(); acl::json_node& a = root.add_array(true); a.add_child(false, true).add_text("name", "zsx").get_parent() .add_child(false, true).add_number("age", 100).get_parent() .add_child(false, true).add_bool("man", true); acl::string buf; json.to_string(&buf); printf("%s\r\n", buf.c_str()); } static void test_build3() { acl::json json; acl::json_node& root = json.get_root(); acl::json_node& a = root.add_array(true); a.add_child(json.create_node().add_text("name", "zsx")) .add_child(json.create_node().add_number("age", (long long) 100)) .add_child(json.create_node().add_bool("man", true)); acl::string buf; json.to_string(&buf); printf("%s\r\n", buf.c_str()); } int main() { test_build1(); test_build2(); test_build3(); return 0; } ``` -------------------------------- ### Fiber Mutex Synchronization with C++ Source: https://context7.com/acl-dev/demo/llms.txt Implements fiber-level mutex locks for synchronizing access to shared resources between concurrent fibers. This example demonstrates how to use `acl::fiber_mutex` to prevent race conditions in a multi-threaded environment managed by ACL fibers. ```cpp #include #include #include class myfiber : public acl::fiber { public: myfiber(acl::fiber_mutex& lock) : lock_(lock) {} protected: void run(void) { for (int i = 0; i < 5; i++) { lock_.lock(); printf("locked by fiber-%u and sleep\r\n", acl::fiber::self()); sleep(1); printf("fiber-%u wakeup\r\n", acl::fiber::self()); lock_.unlock(); } delete this; } private: acl::fiber_mutex& lock_; ~myfiber(void) {} }; int main(void) { acl::fiber_mutex lock; acl::fiber* fb1 = new myfiber(lock); fb1->start(); acl::fiber* fb2 = new myfiber(lock); fb2->start(); acl::fiber::schedule(); return 0; } ``` -------------------------------- ### Fiber-Based Concurrent Redis Hash Operations with ACL-CPP Source: https://context7.com/acl-dev/demo/llms.txt Utilizes ACL-CPP fibers to perform concurrent Redis hash operations. This example demonstrates launching multiple coroutines to execute HSET commands in parallel, showcasing high-performance data manipulation. ```cpp #include #include class fiber_redis : public acl::fiber { public: fiber_redis(acl::redis_client_cluster& cluster) : cluster_(cluster) {} private: ~fiber_redis(void) {} acl::redis_client_cluster& cluster_; void run(void) { const char* key = "hash-key"; for (int i = 0; i < 100; i++) { acl::redis cmd(&cluster_); acl::string name, val; name.format("hash-name-%d", i); val.format("hash-val-%d", i); if (cmd.hset(key, name, val) == -1) { printf("hset error: %s, key=%s, name=%s\r\n", cmd.result_error(), key, name.c_str()); break; } else { printf("hset ok, key=%s, name=%s\r\n", key, name.c_str()); } } delete this; } }; int main(void) { const char* redis_addr = "127.0.0.1:9000"; acl::redis_client_cluster cluster; cluster.set(redis_addr, 0); for (int i = 0; i < 100; i++) { acl::fiber* fb = new fiber_redis(cluster); fb->start(); } acl::fiber::schedule(); return 0; } ``` -------------------------------- ### Redis Hash Operations with ACL-CPP Source: https://context7.com/acl-dev/demo/llms.txt Demonstrates basic Redis hash operations including setting multiple fields (HMSET), expiring keys, and setting individual fields (HSET) with cluster support. It also shows how to retrieve all fields of a hash (HGETALL). ```cpp #include #include int main(void) { acl::redis_client_cluster cluster; cluster.set("127.0.0.1:9001", 0); acl::redis cmd(&cluster); std::map attrs; attrs["name1"] = "value1"; attrs["name2"] = "value2"; attrs["name3"] = "value3"; const char* key = "key"; if (!cmd.hmset(key, attrs)) { printf("hmset error=%s\r\n", cmd.result_error()); return 1; } printf("hmset ok, key=%s\r\n", key); cmd.clear(); int ttl = 5; if (cmd.expire(key, ttl) <= 0) { printf("expire error=%s, key=%s, ttl=%d\r\n", cmd.result_error(), key, ttl); return 1; } printf("expire ok, key=%s, ttl=%d\r\n", key, ttl); cmd.clear(); for (int i = 0; i < 3; i++) { sleep(1); printf("sleep %d seconds\r\n", i + 1); } if (cmd.hset(key, "name4", "value4") == -1) { printf("hset error=%s, key=%s\r\n", cmd.result_error(), key); return 1; } printf("hset ok, key=%s\r\n", key); cmd.clear(); ttl = 5; if (cmd.expire(key, 5) <= 0) { printf("expire error=%s, key=%s, ttl=%d\r\n", cmd.result_error(), key, ttl); return 1; } printf("expire ok, key=%s, ttl=%d\r\n", key, ttl); attrs.clear(); for (int i = 0; i < 4; i++) { sleep(1); printf("sleep %d seconds\r\n", i + 1); } if (!cmd.hgetall(key, attrs)) { printf("hgetall error=%s, key=%s\r\n", cmd.result_error(), key); return 1; } printf("hgetall result for key=%s\r\n", key); for (std::map::const_iterator cit = attrs.begin(); cit != attrs.end(); ++cit) { printf("%s=%s\r\n", cit->first.c_str(), cit->second.c_str()); } return 0; } ``` -------------------------------- ### Build Fiber-Based Echo Server in C++ Source: https://context7.com/acl-dev/demo/llms.txt Illustrates building a high-performance TCP echo server using ACL's fiber coroutines. Each client connection is handled by a dedicated fiber, allowing for efficient concurrent request processing. Requires including `` and ``. ```cpp #include #include class fiber_client : public acl::fiber { public: fiber_client(acl::socket_stream* conn) : conn_(conn) {} protected: void run(void) { printf("fiber-%d-%d running\r\n", get_id(), acl::fiber::self()); char buf[8192]; while (true) { int ret = conn_->read(buf, sizeof(buf), false); if (ret == -1) break; if (conn_->write(buf, ret) == -1) break; } delete conn_; delete this; } private: acl::socket_stream* conn_; ~fiber_client(void) {} }; class fiber_server : public acl::fiber { public: fiber_server(acl::server_socket& ss) : ss_(ss) {} ~fiber_server(void) {} protected: void run(void) { while (true) { acl::socket_stream* conn = ss_.accept(); if (conn == NULL) { printf("accept error %s\r\n", acl::last_serror()); break; } printf("accept ok, fd: %d\r\n", conn->sock_handle()); fiber_client* fc = new fiber_client(conn); fc->start(); } } private: acl::server_socket& ss_; }; int main(void) { acl::acl_cpp_init(); acl::string addr("127.0.0.1:9206"); acl::log::stdout_open(true); acl::server_socket ss; if (ss.open(addr) == false) { printf("listen %s error %s\r\n", addr.c_str(), acl::last_serror()); return 1; } printf("listen %s ok\r\n", addr.c_str()); fiber_server fs(ss); fs.start(); acl::fiber::schedule(); return 0; } ``` -------------------------------- ### HTTPS Client with SSL/TLS and OpenSSL (C++) Source: https://context7.com/acl-dev/demo/llms.txt Establishes secure HTTPS connections using OpenSSL. It allows specifying custom SSL library paths and handles certificate loading. The code demonstrates making repeated requests and managing the SSL configuration. ```cpp #include static void start_test(const char* addr, acl::sslbase_conf& ssl_conf) { acl::http_request req(addr); req.set_ssl(&ssl_conf); const char* data = "hello world!\r\n"; int max = 4; acl::string buf; for (int i = 0; i < max; i++) { req.request_header().set_url("/") .set_keep_alive(true) .set_content_length((long long) strlen(data)) .set_content_type("text/json") .set_host("test.com"); if (!req.request(data, strlen(data))) { printf("Send request error\r\n"); break; } buf.clear(); if (!req.get_body(buf)) { printf("Get response body error!\r\n"); break; } printf("Get: %s", buf.c_str()); fflush(stdout); req.reset(); buf.clear(); } } int main(int argc, char *argv[]) { acl::string addr("127.0.0.1:1900"); #ifdef __APPLE__ acl::string libpath("/usr/local/lib/libcrypto.dylib; /usr/local/lib/libssl.dylib"); #else acl::string libpath("/usr/local/lib64/libcrypto.so; /usr/local/lib64/libssl.so"); #endif acl::acl_cpp_init(); acl::log::stdout_open(true); const std::vector& libs = libpath.split2("; \t"); if (libs.size() != 2) { printf("invalid libpath=%s\r\n", libpath.c_str()); return 1; } acl::openssl_conf::set_libpath(libs[0], libs[1]); if (!acl::openssl_conf::load()) { printf("load %s error\r\n", libpath.c_str()); return 1; } acl::sslbase_conf* ssl_conf = new acl::openssl_conf(false); start_test(addr, *ssl_conf); delete ssl_conf; return 0; } ``` -------------------------------- ### Blocking TCP Echo Server with C++ Source: https://context7.com/acl-dev/demo/llms.txt Creates a simple blocking TCP server using ACL library that accepts a single connection and echoes received data back to the client. It initializes ACL, sets up a listening socket, accepts a connection, and enters a loop to read and write data. ```cpp #include static void echo(acl::socket_stream& conn) { char buf[8192]; while (true) { int ret = conn.read(buf, sizeof(buf), false); if (ret == -1) { break; } if (conn.write(buf, ret) == -1) { break; } } } int main(void) { acl::acl_cpp_init(); acl::string addr("127.0.0.1:9206"); acl::log::stdout_open(true); acl::server_socket ss; if (ss.open(addr) == false) { printf("listen %s error %s\r\n", addr.c_str(), acl::last_serror()); return 1; } printf("listen %s ok\r\n", addr.c_str()); acl::socket_stream* conn = ss.accept(); if (conn == NULL) { printf("accept error %s\r\n", acl::last_serror()); return 1; } printf("accept one, fd=%d, from=%s\r\n", conn->sock_handle(), conn->get_peer(true)); echo(*conn); delete conn; printf("finished!\r\n"); return 0; } ``` -------------------------------- ### Create Fiber-Based Coroutines in C++ Source: https://context7.com/acl-dev/demo/llms.txt Demonstrates the creation of lightweight user-space threads (fibers) for concurrent programming using the ACL library. Each fiber runs independently and is managed by the ACL scheduler. Requires including `` and ``. ```cpp #include #include class myfiber : public acl::fiber { public: myfiber(void) {} protected: ~myfiber(void) {} // @override void run(void) { printf("fiber-%d-%d running\r\n", get_id(), acl::fiber::self()); delete this; } }; int main(void) { acl::acl_cpp_init(); acl::log::stdout_open(true); for (int i = 0; i < 10; i++) { acl::fiber* f = new myfiber(); f->start(); } acl::fiber::schedule(); return 0; } ``` -------------------------------- ### Compile ACL C++ Demos Source: https://github.com/acl-dev/demo/blob/master/COMPILE.md Commands to compile the C++ demos for ACL. This requires navigating to the respective demo directories (`demo/c++` and `demo/c++1x`) and running `make`. ```shell #cd demo/c++; make #cd demo/c++1x; make ``` -------------------------------- ### Multi-threading with Thread Box (Mailbox) in C++ Source: https://context7.com/acl-dev/demo/llms.txt This C++ code demonstrates creating and managing OS threads using ACL++. It highlights inter-thread communication through a thread-safe mailbox (tbox) for message passing. The `mythread` class sends messages to a shared `acl::tbox`, and the main thread retrieves and processes these messages, showcasing a common pattern for producer-consumer scenarios. ```cpp #include class mythread : public acl::thread { public: mythread(acl::tbox& tbox) : buf_(NULL), tbox_(tbox) {} ~mythread(void) { delete buf_; } private: void* run(void) { printf("hello world! thread-%lu\r\n", acl::thread::thread_self()); buf_ = new acl::string; (*buf_) << "hello world: " << acl::thread::thread_self(); tbox_.push(buf_); return buf_; } acl::string* buf_; acl::tbox& tbox_; }; int main(void) { std::vector threads; acl::tbox tbox; for (size_t i = 0; i < 10; i++) { acl::thread* thr = new mythread(tbox); threads.push_back(thr); thr->set_detachable(false); thr->start(); } for (size_t i = 0; i < 10; i++) { acl::string* buf = tbox.pop(); printf("|%s|\r\n", buf->c_str()); } for (std::vector::iterator it = threads.begin(); it != threads.end(); ++it) { acl::string* buf; (*it)->wait((void**) &buf); printf("thread exit: %s\r\n", buf->c_str()); delete *it; } printf("All threads finished!\r\n"); return 0; } ``` -------------------------------- ### Benchmark JSON Parsing with Various Libraries Source: https://github.com/acl-dev/demo/blob/master/benchmark/json/readme.txt This section details the performance results of parsing 100,000 JSON objects using different libraries. It measures the count, cost (ms), speed, and size (MB) for each library. Note that simdjson shows a significantly different size compared to others. ```bash ./json -f json1.txt -n 100000 ``` ```text yyjson: count=100000, cost=90.00 ms, speed=1111111.11, size=658.04 MB simdjson: count=100000, cost=3242.00 ms, speed=30845.16, size=18.27 MB cjson: count=100000, cost=935.00 ms, speed=106951.87, size=63.34 MB rapidjson: count=100000, cost=157.00 ms, speed=636942.68, size=377.22 MB jtjson: count=100000, cost=976.00 ms, speed=102459.02, size=60.68 MB acl_cppjson: count=100000, cost=928.00 ms, speed=107758.62, size=63.82 MB acl_cjson: count=100000, cost=888.00 ms, speed=112612.61, size=66.69 MB ``` -------------------------------- ### HTTP POST Request with URL-Encoded Form Data (C++) Source: https://context7.com/acl-dev/demo/llms.txt Sends an HTTP POST request with URL-encoded form data and custom headers. It utilizes acl::url_coder for encoding and acl::http_request for managing the request. The output includes the request headers, body, and response. ```cpp #include int main(void) { acl::url_coder coder; coder.set("name1", "value1") .set("name2", "value2"); acl::string body(coder.to_string()); acl::http_request req("www.baidu.com:80"); acl::http_header& hdr = req.request_header(); hdr.set_url("/") .set_method(acl::HTTP_METHOD_POST) .set_content_type("application/x-www-form-urlencoded") .set_content_length(body.size()); if (!req.request(body, body.size())) { printf("request error\r\n"); return 1; } printf("-------------------------------------------------------\r\n"); acl::string buf; hdr.build_request(buf); printf("[%s]\r\n", buf.c_str()); printf("[%s]\r\n", body.c_str()); printf("-------------------------------------------------------\r\n"); buf.clear(); acl::http_client* conn = req.get_client(); conn->sprint_header(buf); printf("[%s]\r\n", buf.c_str()); body.clear(); if (!req.get_body(body)) { printf("get_body error!\r\n"); return 1; } printf("[%s]\r\n", body.c_str()); return 0; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.