我刚开始用 C++ 编码,我正在尝试构建一个多线程服务器,但我遇到了一些错误。首先,这是我得到的代码:
while(true){
printf("waiting for a connection\n");
csock = (int*)malloc(sizeof(int));
if((*csock = accept( hsock, (sockaddr*)&sadr, &addr_size))!= -1)
{
printf("---------------------\nReceived connection from %s\n",inet_ntoa(sadr.sin_addr));
//std::thread th(&Network::SocketHandler, NULL);
std::thread th(Network::SocketHandler, (void*)csock);
th.detach();
}
else
{
fprintf(stderr, "Error accepting %d\n", errno);
}
}
}
void Network::SocketHandler(void* lp)
{
int *csock = (int*)lp;
char buffer[1024];
int buffer_len = 1024;
int bytecount;
memset(buffer, 0, buffer_len);
if((bytecount = recv(*csock, buffer, buffer_len, 0))== -1){
fprintf(stderr, "Error receiving data %d\n", errno);
}
printf("Received bytes %d\nReceived string \"%s\"\n", bytecount, buffer);
strcat(buffer, " SERVER ECHO");
if((bytecount = send(*csock, buffer, strlen(buffer), 0))== -1){
fprintf(stderr, "Error sending data %d\n", errno);
}
printf("Sent bytes %d\n", bytecount);
}
在此行编译时出现错误:
std::thread th(Network::SocketHandler, (void*)csock);
说: std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (Network:: )(int ); _Args = {void*}] 没有已知的参数 1 从 '' 到 'void (Network:: &&)(int )' 的转换</p>
我怎样才能解决这个问题?还是有更好的方法来创建多线程服务器任何其他帖子的示例?