我正在编写一个简单的 TCP 服务器。我想到的模型是服务器在主线程中接受客户端连接并将它们交给另一个线程,以便服务器可以再次监听连接。我使用的代码的相关部分发布在下面:
接受连接:
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));
}
}
在这里, processingThreadGroup 是一个 boost::thread_group 实例。在工艺方法中:
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);
}
但是,当我调试代码时,我看到当调用处理线程时,主线程不再接受连接。数据仅在 process() 方法内读取。主线程似乎不再运行。我采取的方法有什么问题以及纠正它的任何建议?
编辑:我想我在这里找到了问题,并将其更新为答案。不会接受,因为我回答了我自己的问题。谢谢大家的帮助!