Writing a C++ webserver is a big task. I wrote one for my hobby computer algebra system and it's pretty large. If you'd like to see the main loop of my server, take a look at:
https://github.com/tmilev/calculator/blob/master/src/webserver.cpp#L4255
for the server and
https://github.com/tmilev/calculator/blob/master/src/webserver.cpp#L4496
for the worker processes. The guide I used to write the first version of this server is here:
https://beej.us/guide/bgnet/html/single/bgnet.html
The most important question you need to answer when writing a C++ server is: what architecture will you use? I know of 3 approaches. Here are they in order of increasing complexity.
- Approach 1. Process incoming connections in separate processes. Use a simple server listen loop (possibly single-threaded, as is the case with my server). Fork out for each new incoming connection. This approach is quite safe, stable, simple, and has good performance too.
I am not 100% sure if that still is the case, but I think this is how the Apache web server works.
This is also how my web server works.
- Approach 2. Same as approach 1, but use multi-threading rather than separate processes to handle new incoming connections.
This has the disadvantage that, if your system is overloaded and crashes, your main server loop burns. If you choose this approach, you **WILL** need to invest in server monitoring/auto-server restart.
- Approach 3. Handle incoming packets as in Approach 2. However, each of you handling threads handles exclusively input/output operations and uses selects/polls to manage multiple open connections at the same time. Once input/output is received:
- pile all TCP packets onto a queue of unprocessed messages
- offload message processing to worker threads.
- When worker threads are done, they pile back their ready-to-be-sent packets in a processed messages queue.
- Those are in turn consumed by your input/output threads.
From what I understand - please do correct me if I am wrong - the Node.js server (whose core is written, I heard, in C++) has an architecture along these lines.