I am writing a simple TCP server. The model I am is a server that accepts client connections on the main thread and passes them to another thread so that the server can listen on connections again. The following are the relevant parts of the code that I used:
Acceptance of connections:
void startServer () { int serverSideSocket = 0; int clientSideSocket = 0; serverSideSocket = socket(AF_INET, SOCK_STREAM, 0); if (serverSideSocket < 0) { error("ERROR opening socket"); exit(1); } clientAddressLength = sizeof(clientAddress); memset((char *) &serverAddress, 0, sizeof(serverAddress)); memset((char *) &clientAddress, 0, clientAddressLength); serverAddress.sin_family = AF_INET; serverAddress.sin_addr.s_addr = INADDR_ANY; serverAddress.sin_port = htons(32000); if (bind(serverSideSocket, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) < 0) { error("ERROR on binding"); exit(1); } listen(serverSideSocket, SOMAXCONN); while(true) { clientSideSocket = accept(serverSideSocket, (struct sockaddr *) &clientAddress, &clientAddressLength); if (clientSideSocket < 0) error("ERROR on accept"); processingThreadGroup->create_thread(boost::bind(process, clientSideSocket, this)); } }
Here, the ThreadGroup handler is an instance of boost :: thread_group. In the process method:
void process (int clientSideSocket, DataCollector* collector) { int numberOfCharactersRead = 0; string buffer; do { char msgBuffer[1000]; numberOfCharactersRead = recv(clientSideSocket, msgBuffer, (1000 - 1), 0); if (numberOfCharactersRead < 0) { //display error close(clientSideSocket); } else if (numberOfCharactersRead == 0) close(clientSideSocket); else { printf("%s", msgBuffer); memset(msgBuffer, 0, 1000); } } while (numberOfCharactersRead > 0); }
However, when I debug the code, I saw that when the processing thread was called, the main thread no longer accepts the connection. Data is read only inside the process () method. The main thread does not seem to work anymore. What is the problem with the approach I took and suggestions for fixing it?
EDIT: I think I found the problem here and updated it as an answer. I do not agree, as I answered my question. Thanks for helping everyone!