Simple Web Server
Cpp
#include "crow.h"
int main()
{
crow::SimpleApp app;
CROW_ROUTE(app, "/")([](){
return "Hello world";
});
app.port(8000).multithreaded().run();
}
JavaScript (NodeJS)
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
What This Code Does
The goal is to describe a basic web-server that responds with
the string "Hello, World" to the root path of the server (/
).
What's the Same
The JavaScript solution uses NodeJS (a server-side JavaScript platform) to implement a simple server with a single-route (example is taken directly from the nodejs.org website. The C++ solution, in similar fashion, uses Crow to define a simple route using very similar mechanisms (example taken from the Crow GitHub README).
What's Different
C++, as of C++-17, does not have any standard networking features and thus no standard libraries for creating web-servers. Crow is a simple 3rd-party framework in the style of Sinatra/Flask for creating simple web apps. Other frameworks such as Boost Beast or Cutelyst also exist to serve this need.
It is worth noting that networking in the standard library is coming via the Networking
TS. This
TS has been published, which essentially
means these features are available in a experimental/beta mode as people try them out allowing for any
minor adjustments before being "written in stone." You can find the status for all specifications on the
ISO CPP website.
Asynchronous networking I/O can also be achieved today with
Boost.Asio,
which currently follows the Networking TS in it's implementation.