我想accept()
在一个单独的线程中处理该方法,以避免在等待连接时出现一般冻结。
代码(*仅限服务器!*):
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno;
socklen_t clilen;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int n;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
listen(sockfd,5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
bzero(buffer,256);
n = read(newsockfd,buffer,255);
n = write(newsockfd,"Message : ",18);
close(newsockfd);
close(sockfd);
return 0;
}
如何在此代码中创建一个单独的线程,防止accept()
调用冻结程序。作为奖励,我想处理多个accept()
(因此套接字在收到消息后不会关闭,而是继续侦听并接受请求)。