Seasocks - a quick and easy websocket server in C++

I’d like to draw attention to an open-source library that I open sourced a while ago: Seasocks.

Seasocks is a simple-to-use, lightweight, embeddable C++ library that implements HTTP and websockets. It has a simple way of serving static content and even some dynamic content, but its main raison d’ĂȘtre is for websocket-based command and control.

It has no external library dependencies, and only requires C++11 features such as GCC 4.7 and above and Clang 3.4 already support.

Serving static files is as simple as:

void serve() {
    Server server(make_shared<PrintfLogger>();
    server.serve("web", 9090);
}

Websockets are a little more involved, but not a whole deal more. He’s the skeleton of a chat client that simply broadcasts any input from a client to all other connected parties.

struct ChatHandler : WebSocket::Handler {
    set<WebSocket *> connections;
    void onConnect(WebSocket *socket) override 
    { connections.insert(socket); }
    void onData(WebSocket *, const char *data) override 
    { for (auto c : connections) c->send(data); }
    void onDisconnect(WebSocket *socket) override 
    { connections.erase(socket); }
};

void chat() {
    Server server(make_shared<PrintfLogger>());
    server.addWebSocketHandler(
        "/chat", make_shared<ChatHandler>());
    server.serve("web", 9090);
}

There are more examples in the source.

There are other websocket libraries for C++ out there, but Seasocks has been the workhorse of our C++ command and control for over four years now and has proven to be a pretty reliable bit of software.

Filed under: Coding
Posted at 03:15:00 GMT on 14th March 2015.

About Matt Godbolt

Matt Godbolt is a C++ developer working in Chicago for Aquatic. Follow him on Mastodon.