Reputation: 1719
I am trying to build a TCP server on windows with c++. I know that if I want to communicate with all clients, I can use threads. One thread handles one client. I am wondering is there any other method to handle this task, for example:
std::vector<SOCKET> clients;
while(clients.size() < 1024){
SOCKET ss = accept(ListenSocket, NULL, NULL);
clients.push_back(ss);
}
while(true){
SOCKET speckingClient = Function(clients);
iResult = recv(speckingClient, recvbuf, recvbuflen, 0);
// the rest of the function...
}
The above code cannot be run but hopefully showing what I am looking for.
Upvotes: 0
Views: 322
Reputation: 264719
Yes there is a better technique.
The preferred method is to use select()
(or more likely one of its replacements). Optionally with a thread pool.
select()
allows you wait for input on multiple ports simultaneously. When input is available (or space is available for write) select returns allowing you to processes all available inputs/outputs on all ports.
You should look up the the C10K problem on google. You will find lots of articles on how to write a server that handles many incoming client requests.
Upvotes: 3