Hi, I'm quite new to C++ but I want to write a simple socket script for testing propose. It will never, but should be able to handle hundreds of client at the same time. I'm worried there could be a bottleneck thinking of latency.
Because of this I guess more than one thread is needed to handle so many clients.
But here's my problem: Could someone of you tell me (no code, just tell me the idea) how to manage sockets with multiple threads?
I could make an own thread for each connection, but I think this are way too many.
An other way could be, every thread handles 10 connections for example. But I don't know how to coordinate such a system now. I guess this could be quite easy thinking about SMTP, HTTP and so on, but thinking of a chat, I don't know how to handle this.
And maybe there is an other, better way of handling such a task in general ;)
Hope you can help me so I'm able to understand those "basics".
In UNIX/Linux, there are basically two ways: Fork another process when your server gets a connection, or start a new thread when your server gets a connection.
The very basic idea is this:
1. Your server obtains a socket with the socket() call
2. Your server binds to that socket with the bind() call.
3. Your server calls listen().
4. When listen() returns, either fork a new process or create a new thread (there are pros and cons for both.)
5. That new process or thread will inherit the socket
6. New process or thread calls accept()
7. When accept() returns, the new process or thread calls read() or recv() and the rest is up to you!
I hope this helps.
The decision you make about processes verses threads probably depends on what kind of work each socket connection will be doing.
The best book I've ever read about socket programming is "Unix Network Programming."
Thanks for this! But don't you think creating one thread / process for each connection could cause an overload or latency problems after some time?
Thinking of an chat, what's the best way of handling this, because you need to receive a message on one socket and submit it to many other threads/processes with each one different socket. Couldn't some messages disappear if two users would send messages in a very short time?
Thanks for this! But don't you think creating one thread / process for each connection could cause an overload or latency problems after some time?
Yes, of course, it would. That is why it is not a recommended solution. Correct solution is to keep a pool of threads or processes ready to serve requests or even better, to handle everything in one thread per cpu core.