Patouf
Patouf

Reputation: 119

Accept() in a thread to avoid "blocking" socket

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).

Upvotes: 0

Views: 3421

Answers (1)

mark
mark

Reputation: 5469

You can use select to know if there's a connection waiting that can be accepted, but my approach would be to put all the socket/bind/listen/accept in a thread, put the accept into a loop, and spin off new threads with the connections as they arrive.

Upvotes: 2

Related Questions