In C++, I’ve read some tutorials to create a server which can accept connections from multiple clients. They suggest using async socket, but i don’t really know why we should choose async over none-blocking mode. And what’s about the ideas that use multi-threading? is it better than using async socket? Thanks!!
Share
Since you’re requesting a solution in C++, boost asio is imo the best async io library there is.
I assume you’re talking about the “one thread per client” solution when refering to “multi-threading”, which is generally a very bad idea for servers who expect many clients in a short time frame or connected at the same time.
Threads are way to resource consuming for this use, plus you have to take care of mutual exclusion, which in combination with blocking calls can drive you into deadlocks very fast. And thats the least worst of what you can run into.
Additionally on that, it’s very easy for an attacker to exploit your server to stuck. You will spend much time on trying to design your code so that this will be avoided, which leads you into having an unreadable, hard to update and error phrone code.
In boost.asio the specified thread(s) ( those who call io_service::run ) will only do work when there is actually work to do, directly leading you into the object assigned to the task.
So technically async is also blocking, with the difference that only the scheduler waits for work to do, while those functions you add work with ( connect, send, receive, … ) will return immediately.