I'd like to handle the accept()
method in a separate thread, to avoid the general freeze while it waits for a connection.
The code (* server only! * ):
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;
}
How can I create a separate thread within this code, preventing the accept()
call to freeze the program. As a bonus, I'd like to handle multiple accept()
(so the socket does not close itseld after the message is received, but continues to listen and accept requests).
您可以使用select来了解是否有可以接受的连接等待,但我的方法是将所有socket / bind / listen / accept放入一个线程中,将accept放入一个循环中,然后使用他们到达时的联系。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.