I have to do a multithreaded TCP server class that launch a server that can handle up to 4 client at the time but when a client disconnect, the server quit without any .
i have a start function that set all up and launch a new thread with the "server loop" function :
void server_loop()
{
std::cout << "Server started on port " << port_ << "\n";
while (is_running_) {
int client_socket = accept(server_socket_, nullptr, nullptr);
if (client_socket < 0) {
std::cerr << "ERRNO: " << errno << std::endl;
if(errno != 53) {
std::cerr << "Error: cannot accept client connection\n";
}
continue;
}
// Acquire a lock on the client_sockets_mutex_ before accessing the client_sockets_ vector
{
std::lock_guard<std::mutex> lock(client_sockets_mutex_);
if (client_sockets_.size() >= MAX_CLIENTS) {
std::cerr << "Error: maximum number of clients reached\n";
close(client_socket);
continue;
}
client_sockets_.push_back(client_socket);
std::cout << "Client connected (" << client_sockets_.size() << "/" << MAX_CLIENTS << ")\n";
}
// Start a new thread to handle the client communication
std::thread(&TcpServer::handle_client, this, client_socket).detach();
}
}
this create a new thread with the handle client function which is :
void handle_client(int client_socket) {
// loop until the client disconnects
while (true) {
// generate a new ID and send it to the client
unsigned int id = get_unique_id();
std::string id_str = std::to_string(id) + "\n";
int res = send(client_socket, id_str.c_str(), id_str.size(), 0);
if (res < 0) {
std::cerr << "Error sending data to client: " << strerror(errno) << std::endl;
break;
}
// wait for 1 second before sending the next ID
std::this_thread::sleep_for(std::chrono::seconds(1));
}
// remove the client socket from the list of connected clients
{
std::lock_guard<std::mutex> lock(client_sockets_mutex_);
auto it = std::find(client_sockets_.begin(), client_sockets_.end(), client_socket);
if (it != client_sockets_.end()) {
client_sockets_.erase(it);
std::cout << "Client disconnected (" << client_sockets_.size() << "/" << MAX_CLIENTS << ")\n";
}
}
// close the client socket
close(client_socket);
}
My problem is that when i connect to it with nc and i exit it using Ctrl+C, all my program exit while I want it to wait any upcoming client.
Do you guys have any clue, from where it could come from ?