I want to write a TCP/IP server in C++ (using bind()
, accept()
etc.) that can deal with multiple clients connecting to it at the same time.
I have read a few topics about this, and everyone is suggesting the following (dirty pseudocode coming up):
set up server, bind it
while (1) {
accept connection
launch new thread to handle it
}
Which would work totally fine on a machine that has multiple threads. But my target system is a single core machine without any hardware threads. For a little test, I tried launching multiple threads via std::thread
on the system but they were executed one after the other. No parallel goodness :(
That makes it impossible to implement the algorithm above. I mean, I'm sure it can be done, I just don't know how, so I would really appreciate any help.
You don't need threads, you need asynchronous or "event-driven" programming. This can be done with select() if you want cross-platform, or epoll() if you're on Linux and want to support thousands of clients at once.
But you don't need to implement this all from scratch--you can use Boost ASIO (some of which may become part of C++17) or a C library like libevent or libev or libuv. Those will handle a bunch of subtle details for you, and help you get more quickly to the real business of your application.
I am going to take a guess about what your actual code looks like.
The problem with this code is that the thread's destructor is called when the loop reiterates. This will cause an exception to be thrown since the destructor will detect the thread context is still active.
To avoid that problem, you can detach the thread object from the active context.
What follows is a mostly complete example (without error checking). This routine creates an accepting socket for a server specification (which is "host:port" for a particular interface, or ":port" for any interface).
The accepting loop routine creates the listening socket, and then launches threads to handle each new incoming connection.
The new connection handler just outputs a
.
followed by a newline every second. Theisclosed()
function can be found among answers to this question.And then the main function just ties it all together.