Sandbird HTTP Server

repository·master·Indexed 42 days ago

https://github.com/rxi/sandbird

A tiny, embeddable, asynchronous HTTP server written in C89 for Linux, OSX, and Windows. It provides a single-threaded event-driven architecture using functions like sb_new_server(), sb_poll_server(), and sb_close_server() to handle requests without multi-threaded overhead.

Tokens
586
Snippets
4
Records
5
Agent score
3%

What's inside Sandbird

  1. Integrate Sandbird into your project

    master
    Sandbird is a tiny, embeddable HTTP server written in C89. To use it, drop sandbird.c and sandbird.h into your existing project and compile them along with your source code. It is compatible with Linux, OSX, and Windows. The server operates asynchronously without using threads; instead, it uses an event handler that is invoked when events (such as requests) occur.
  2. Run the server event loop with sb_poll_server

    master

    Sandbird requires you to call sb_poll_server() regularly to process new connections and existing requests. The function accepts a timeout value in milliseconds. Setting the timeout to 0 makes the function non-blocking.

    for (;;) {
      sb_poll_server(srv, 1000);
    }
  3. Initialize and start a Sandbird server

    master

    To start the server, initialize an sb_Options struct, set the required fields, and pass it to sb_new_server(). At a minimum, you must set port and handler. If sb_new_server() returns NULL, the server failed to start (likely due to a socket binding error). A non-NULL return value indicates the server is successfully listening.

    sb_Server *srv;
    sb_Options opt;
    
    memset(&opt, 0, sizeof(opt));
    opt.port = "8000";
    opt.handler = event_handler;
    
    srv = sb_new_server(&opt);
  4. Implement an event handler for Sandbird

    master

    You must define an event handler function with the signature int handler(sb_Event *e). Inside the handler, you check the event type (e.g., SB_EV_REQUEST) and use stream functions to respond to the client. The handler should return SB_RES_OK to indicate the event was handled successfully.

    static int event_handler(sb_Event *e) {
      if (e->type == SB_EV_REQUEST) {
        sb_send_status(e->stream, 200, "OK");
        sb_send_header(e->stream, "Content-Type", "text/plain");
        sb_writef(e->stream, "Hello world");
      }
      return SB_RES_OK;
    }