acl-dev / acl

C/C++ server and network library, including coroutine,redis client,http/https/websocket,mqtt, mysql/postgresql/sqlite client with C/C++ for Linux, Android, iOS, MacOS, Windows, etc..
https://acl-dev.cn
GNU Lesser General Public License v3.0
2.83k stars 937 forks source link
coroutine cplusplus database fiber http http-client http-server https memcached-clients mqtt-client mqtt-protocol network redis redis-client smtp websocket

中文简体

Acl -- One Advanced C/C++ Library for Unix/Windows

0. About Acl project

The Acl (Advanced C/C++ Library) project a is powerful multi-platform network communication library and service framework, suppoting LINUX, WIN32, Solaris, FreeBSD, MacOS, AndroidOS, iOS. Many applications written by Acl run on these devices with Linux, Windows, iPhone and Android and serve billions of users. There are some important modules in Acl project, including network communcation, server framework, application protocols, multiple coders, etc. The common protocols such as HTTP/SMTP/ICMP//MQTT/Redis/Memcached/Beanstalk/Handler Socket are implemented in Acl, and the codec library such as XML/JSON/MIME/BASE64/UUCODE/QPCODE/RFC2047/RFC1035, etc., are also included in Acl. Acl also provides unified abstract interface for popular databases such as Mysql, Postgresql, Sqlite. Using Acl library users can write database application more easily, quickly and safely.

Architecture diagram: Overall architecture diagram



1. The six most important modules

As a C/C++ foundation library, Acl provides many useful functions for users to develop applications, including six important modules: Network, Coroutine, HTTP, Redis client, MQTT, and Server framework.

1.1. Basic network module

1.2. Coroutine

The coroutine module in Acl can be used on multiple platforms, and there are many engineering practices in some important projects.

1.3. HTTP module

Supports HTTP/1.1, can be used in client and server sides.

1.4. Redis client

The redis client module in Acl is powerful, high-performance and easy to use.

1.5. MQTT module

The MQTT 3.1.1 version has been implemented in Acl, which has a stream parser, so can be used indepedentily of any IO mode.

1.6. Server framework

The most important module in Acl is the server framework, which helps users quickly write back-end services, such as web services. Tools in app/wizard can help users generate one appropriate service code within several seconds. The server framework of Acl includes two parts, one is the services manager, the other is the service written by Acl service template. The services manager named acl_master in Acl comes from the famous MTA Postfix, whose name is master, and acl_master has many extensions to master in order to be as one general services manager. There are six service templates in Acl that can be used to write application services, as below:

2. The other important modules

2.1. MIME module

MIME(Multipurpose Internet Mail Extensions) format is widely used in email application. MIME format is too important that it can be used not only for email applications, but also for Web applications. MIME RFC such as RFC2045/RFC2047/RFC822 has been implemented in Acl. Acl has a MIME data stream parser that is indepedent of the IO model, so it can be used by synchronous or asynchronous IO programs.

2.2. Codec module

Thare are some common codecs in Acl, such as Json, Xml, Base64, Url, etc., which are all stream parser and indepedent of IO communication. Json is very popular, so Acl also provides serialization/deserialization tools which can be used to transfer between Json data and C struct objects, which greatly improves the programming efficiency.

2.3. Database module

The unified database interface in Acl is designed to easily and safely operate thease well-known open source databases such as Mysql, Postgresql and SQLite. The SQL codec is designed to escape the charactors to avoid the DB SQL attacks. When users use Acl to write database applications, Acl will dynamically load the dynamic libraries of Mysql, Postgresql or SQLite. The advantage of dynamic loading is that users who don't need the database functionality don't care about it at all.

2.4. Connection pool manager

There's a genernal connection pool manager in Acl, which is used widely by the other important modules, including redis, database, and http modules, etc.

2.5. The other client libraries

In addition to redis client, Acl also implements some other important client libraries, such as memcached client, handler-socket, beanstalk, disque and so on.

2.6. DNS module

Acl not only wraps the system DNS API, such as getaddrinfo and gethostbyname, but also implements the DNS protocol specified in RFC1035. Users can use the DNS module in Acl to implement their own DNS client or server.

3. Platform support and compilation

3.1. Compiling Acl on different platforms

Acl project currently supports Linux, Windows, MacOS, FreeBSD, Solaris, Android, and iOS.

3.2. Precautions when compiling on Windows

There are a few things to keep in mind when using dynamic libraries in a WIN32 environment:

4. Quick start

4.1. The first demo with Acl

#include <iostream>
#include "acl_cpp/lib_acl.hpp"

int main(void) {
  acl::string buf = "hello world!\r\n";
  std::cout << buf.c_str() << std::endl;
  return 0;
}

4.2. Simple TCP server

#include <thread>
#include "acl_cpp/lib_acl.hpp"

void run(void) {
  const char* addr = "127.0.0.1:8088";
  acl::server_socket server;
  if (!server.open(addr)) {  // Bind and listen the local address.
    return;
  }

  while (true) {
    acl::socket_stream* conn = server.accept(); // Wait for connection.
    if (conn == NULL) {
      break;
    }
    std::thread thread([=] {  // Start one thread to handle the connection.
      char buf[256];
      int ret = conn->read(buf, sizeof(buf), false);  // Read data.
      if (ret > 0) {
        conn->write(buf, ret);  // Write the received data.
      }
      delete conn;
    });
    thread.detach();
  }
}

4.3. Simple TCP client

#include "acl_cpp/lib_acl.hpp"

void run(void) {
  const char* addr = "127.0.0.1:8088";
  int conn_timeout = 5, rw_timeout = 10;
  acl::socket_stream conn;
  if (!conn.open(addr, conn_timeout, rw_timeout)) { // Connecting the server.
    return;
  }
  const char data[] = "Hello world!\r\n";
  if (conn.write(data, sizeof(data) - 1) == -1) {  // Send data to server.
    return;
  }
  char buf[256];
  int ret = conn.read(buf, sizeof(buf) - 1, false);
  if (ret > 0) {  // Read from server.
    buf[ret] = 0;
    std::cout << buf << std::endl;
  }
}

4.4. Coroutine TCP server

#include "acl_cpp/lib_acl.hpp"
#include "fiber/go_fiber.hpp"

void run(void) {
  const char* addr = "127.0.0.1:8088";
  acl::server_socket server;
  if (!server.open(addr)) {
    return;
  }

  go[&] {  // Create one server coroutine to wait for connection.
    while (true) {
      acl::socket_stream* conn = server.accept();
      if (conn) {
        go[=] {  // Create one client coroutine to handle the connection.
          char buf[256];
          int ret = conn->read(buf, sizeof(buf), false);
          if (ret > 0) {
            (void) conn->write(buf, ret);
          }
          delete conn;
        };
      }
    }
  };

  acl::fiber::schedule();  // Start the coroutine scheculde process.
}

4.5. One Http client

#include "acl_cpp/lib_acl.hpp"

bool run(void) {
  acl::http_request conn("www.baidu.com:80");
  acl::http_header& header = conn.request_header()
  header.set_url("/")
    .set_keep_alive(false);
    .set_content_type("text/html");

  if (!conn.request(NULL, 0)) {
    return false;
  }
  int status = conn.http_status();
  if (status != 200) {
    return false;
  }
  long long len = conn.body_length();
  if (len <= 0) {
    return true;
  }
  acl::string buf;
  if (!conn.get_body(body)) {
    return false;
  }
  return true;
}

4.6. Coroutine Http server

#include "acl_cpp/lib_acl.hpp"  // Must before http_server.hpp
#include "fiber/http_server.hpp"

static char *var_cfg_debug_msg;
static acl::master_str_tbl var_conf_str_tab[] = {
  { "debug_msg", "test_msg", &var_cfg_debug_msg },
  { 0, 0, 0 }
};

static int  var_cfg_io_timeout;
static acl::master_int_tbl var_conf_int_tab[] = {
  { "io_timeout", 120, &var_cfg_io_timeout, 0, 0 },
  { 0, 0 , 0 , 0, 0 }
};

int main(int argc, char* argv[]) {
  const char* addr = "0.0.0.0|8194";
  const char* conf = argc >= 2 ? argv[1] : NULL;
  acl::http_server server;

  // Call the methods in acl::master_base class .
  server.set_cfg_int(var_conf_int_tab).set_cfg_str(var_conf_str_tab);

  // Call the methods in acl::http_server .
  server.on_proc_init([&addr] {
    printf("---> after process init: addr=%s, io_timeout=%d\r\n", addr, var_cfg_io_timeout);
  }).on_proc_exit([] {
    printf("---> before process exit\r\n");
  }).on_proc_sighup([] (acl::string& s) {
    s = "+ok";
    printf("---> process got sighup\r\n");
    return true;
  }).on_thread_accept([] (acl::socket_stream& conn) {
    printf("---> accept %d\r\n", conn.sock_handle());
    return true;
  }).Get("/", [](acl::HttpRequest&, acl::HttpResponse& res) {
    std::string buf("hello world1!\r\n");
    res.setContentLength(buf.size());
    return res.write(buf.c_str(), buf.size());
  }).Post("/json", [](acl::HttpRequest& req, acl::HttpResponse& res) {
    acl::json* json = req.getJson();
    if (json) {
      return res.write(*json);
    } else {
      std::string buf = "no json got\r\n";
      res.setContentLength(buf.size());
      return res.write(buf.c_str(), buf.size());
    }
  }).run_alone(addr, conf);

  return 0;
}

4.7. One redis client

#include <thread>
#include "acl_cpp/lib_acl.hpp"

static void thread_run(acl::redis_client_cluster& conns) {
  acl::redis cmd(&conns);
  std::map<acl::string, acl::string> attrs;
  attrs["name1"] = "value1";
  attrs["name2"] = "value2";
  attrs["name3"] = "value3";
  acl::string key = "hash-key-1";
  if (!cmd.hmset(key, attrs)) {
    printf("hmset error=%s\r\n", cmd.result_error());
    return;
  }

  attrs.clear();
  if (!cmd.hgetall(key, attrs)) {
    printf("hgetall error=%s\r\n", cmd.result_error());
  }
}

void run(void) {
  const char* addr = "126.0.0.1:6379";
  acl::redis_client_cluster conns;
  conns.set(addr, 0);

  const size_t nthreads = 10;
  std::thread threads[nthreads];
  // Create some threads to test redis using the same conns.
  for (size_t i = 0; i < nthreads; i++) {
    threads[i] = std::thread(thread_run, std::ref(conns));
  }
  // Wait for all threads to exit
  for (size_t i = 0; i < nthreads; i++) {
    threads[i].join();
  }
}

5. More about

5.1. Samples

There are a lot of examples in the acl library for reference, please refer to: SAMPLES.md

5.2. More simple demos

There are many small demos showing how to use acl library easily in Demos

5.3. FAQ

If you have some questions when using Acl, please see FAQ.md.

5.4. License

5.5. Reference

5.6. Thanks

Thanks .