belle

An HTTP / Websocket library in C++17 using Boost.Beast and Boost.ASIO.


belle

/

example

/

server

/

chat

/

src

/

main.cc

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
// belle chat example

#include "belle.hh"
namespace Belle = OB::Belle;

#include <ctime>

#include <string>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <optional>
#include <deque>

using namespace std::string_literals;

// basic ring buffer
template<class T>
class Ringbuf
{
public:

  Ringbuf(size_t size = 64):
    _size {size}
  {
  }

  ~Ringbuf()
  {
  }

  Ringbuf& push(T const& t)
  {
    _que.emplace_back(t);

    if (_que.size() > _size)
    {
      _que.pop_front();
    }

    return *this;
  }

  Ringbuf& shrink_to_fit()
  {
    while (_que.size() > _size)
    {
      _que.pop_front();
    }

    return *this;
  }

  std::deque<T> const& get() const
  {
    return _que;
  }

  size_t max_size() const
  {
    return _size;
  }

  Ringbuf max_size(size_t size)
  {
    _size = size;

    if (_que.size() > _size)
    {
      shrink_to_fit();
    }

    return *this;
  }

  Ringbuf& clear()
  {
    _que.clear();

    return *this;
  }

  size_t size() const
  {
    return _que.size();
  }

  bool empty() const
  {
    return _que.empty();
  }

  T& operator[](size_t n)
  {
    return _que.at(n);
  }

  T const& operator[](size_t n) const
  {
    return _que.at(n);
  }

  T& at(size_t n)
  {
    return _que.at(n);
  }

  T const& at(size_t n) const
  {
    return _que.at(n);
  }

private:

  size_t _size;
  std::deque<T> _que;
}; // class Ringbuf

// convert object into a string
template<class T>
std::string to_string(T t)
{
  std::stringstream ss;
  ss << t;

  return ss.str();
}

// read a file into a string
std::optional<std::string> file(std::string const& str);
std::optional<std::string> file(std::string const& str)
{
  std::ifstream file {str};

  if (! file.is_open())
  {
    return {};
  }

  file.seekg(0, std::ios::end);
  size_t size (static_cast<size_t>(file.tellg()));
  std::string content (size, ' ');
  file.seekg(0);
  file.read(&content[0], static_cast<std::streamsize>(size));

  return content;
}

int main(int argc, char *argv[])
{
  // init the server
  Belle::Server app;

  // set the listening address
  std::string address {"127.0.0.1"};
  app.address(address);

  // set the listening port
  int port {8080};
  app.port(port);

  // warn if address:port is already in use
  if (! app.available())
  {
    std::cerr << "Warning: '" << address << ":" << port << "' is in use\n";
  }

  // enable serving static files from a public directory
  // if the path is relative, make sure to run the program
  // in the right working directory
  app.public_dir("../public");

  // serve static content from public dir
  // default value is true
  app.http_static(true);

  // serve dynamic content
  // default value is true
  app.http_dynamic(true);

  // accept websocket upgrade requests
  // default value is true
  app.websocket(true);

  // set default http headers
  Belle::Headers headers;
  headers.set(Belle::Header::server, "Belle");
  headers.set(Belle::Header::cache_control, "private; max-age=0");
  app.http_headers(headers);

  // handle the following signals
  app.signals({SIGINT, SIGTERM});

  // set the on signal callback
  app.on_signal([&](auto ec, auto sig)
  {
    // print out the signal received
    std::cerr << "\nSignal " << sig << "\n";

    // get the io_context and safely stop the server
    app.io().stop();
  });

  // store received messages
  std::unordered_map<std::string, Ringbuf<std::string>> chat;

  // total number of connected users
  int user_count {0};

  // add default chat room channels
  app.channels()["/"] = Belle::Server::Channel();
  app.channels()["/new"] = Belle::Server::Channel();

  // add default messages to the '/new' chat room
  chat["/new"].push("'/' shows an overview of the rooms");
  chat["/new"].push("'/<room_name>' go to an existing room or create a new one");
  chat["/new"].push("Try creating a new room called '/dev'");
  chat["/new"].push("The index page, '/', will now show 3 rooms");
  chat["/new"].push("The most popular room gets moved to the top of the index, try playing around with several tabs open");
  chat["/new"].push("The newest comments appear at the top of the page");

  // handle ws connections to index room '/'
  app.on_websocket("/",
  // on data: called after every websocket read
  [](Belle::Server::Websocket_Ctx& ctx)
  {
    // register the route
    // data will be broadcasted in the websocket connect and disconnect handlers
  });

  // handle ws connections to chat rooms '/<chat_room>'
  app.on_websocket("^(/[a-z]+)$",
  // on begin: called once after connected
  [&](Belle::Server::Websocket_Ctx& ctx)
  {
    // the Websocket automatically joins the channel named after the path on connect
    // retrieve and store the path/channel name
    std::string channel {ctx.req.path().at(0)};

    // broadcast the total number of connected users to the channel
    ctx.channels.at(channel).broadcast("1" + std::to_string(ctx.channels.at(channel).size()));

    // check if there is any messages stored
    if (chat.find(channel) != chat.end())
    {
      // send out all previous messages to new user
      for (auto const& e : chat[channel].get())
      {
        ctx.send("0" + e);
      }
    }

    // send welcome message
    ctx.send("0"s + "> welcome to "s + channel);
  },

  // on data: called after every websocket read
  [&](Belle::Server::Websocket_Ctx& ctx)
  {
    // a simple protocol:
    // in the received message,
    // the first character holds an int from 0-9,
    // the remaining characters are the message

    // the Websocket automatically joins the channel named after the path on connect
    // retrieve and store the path/channel name
    std::string channel {ctx.req.path().at(0)};

    // get the message type
    int type {std::stoi(to_string(ctx.msg.at(0)))};

    // determine action
    switch (type)
    {
      case 0:
      chat[channel].push(ctx.msg.substr(1));
      ctx.channels.at(channel).broadcast("0" + ctx.msg.substr(1));
      break;

      default:
      break;
    }
  },

  // on end: called once after disconnected
  [](Belle::Server::Websocket_Ctx& ctx)
  {
    // the Websocket automatically joins the channel named after the path on connect
    // retrieve and store the path/channel name
    std::string channel {ctx.req.path().at(0)};

    // a user has disconnected
    // broadcast the total number of connected users to the channel
    ctx.channels.at(channel).broadcast("1" + std::to_string(ctx.channels.at(channel).size()));
  }
  );

  // set websocket connect callback
  // called once at the very beginning after connected
  app.on_websocket_connect([&](Belle::Server::Websocket_Ctx& ctx)
  {
    // increase total user count
    ++user_count;

    // send room count
    ctx.channels.at("/").broadcast("0" + std::to_string(ctx.channels.size()));
    // send user count
    ctx.channels.at("/").broadcast("1" + std::to_string(user_count));
    for (auto const& e : ctx.channels)
    {
      // send count and room info
      ctx.channels.at("/").broadcast("2" + std::to_string(e.second.size()) + e.first);
    }
  });

  // set websocket disconnect callback
  // called once at the very end after disconnected
  app.on_websocket_disconnect([&](Belle::Server::Websocket_Ctx& ctx)
  {
    // decrease total user count
    --user_count;

    // send room count
    ctx.channels.at("/").broadcast("0" + std::to_string(ctx.channels.size()));
    // send user count
    ctx.channels.at("/").broadcast("1" + std::to_string(user_count));
    for (auto const& e : ctx.channels)
    {
      // send count and room info
      ctx.channels.at("/").broadcast("2" + std::to_string(e.second.size()) + e.first);
    }
  });

  // handle route GET '/'
  // with no set dynamic route for a route ending in a '/' character,
  // the default action is to look for a static file named 'index.html'
  // in the corresponding public directory

  // handle route GET '/<chat_room>'
  app.on_http("^(/[a-z]+)$", Belle::Method::get, [&](Belle::Server::Http_Ctx& ctx)
  {
    // set http response headers
    ctx.res.set("content-type", "text/html");

    // send the file contents
    if (auto res = file(app.public_dir() + "/chat.html"))
    {
      ctx.res.body() = std::move(res.value());
    }
    else
    {
      throw 404;
    }
  });

  // set custom error callback
  app.on_http_error([](Belle::Server::Http_Ctx& ctx)
  {
    // stringstream to hold the response
    std::stringstream res; res
    << "Status: " << ctx.res.result_int() << "\n"
    << "Reason: " << ctx.res.result() << "\n";

    // set http response headers
    ctx.res.set("content-type", "text/plain");

    // echo the http status code
    ctx.res.body() = res.str();
  });

  // print out the address and port
  std::cout
  << "Server: " << address << ":" << port << "\n\n"
  << "Navigate to the following url:\n"
  << "  http://" << address << ":" << port << "/new\n\n";

  // start the server
  app.listen();

  // the server blocks until a signal is received

  return 0;
}
Back to Top