[ACCEPTED]-Accept multiple subsequent connections to socket-sockets
Yes, you can accept()
many times on the listening 10 socket. To service multiple clients, you 9 need to avoid blocking I/O -- i.e., you 8 can't just read from the socket and block 7 until data comes in. There are two approaches: you 6 can service each client in its own thread 5 (or its own process, by using fork()
on UNIX systems), or 4 you can use select()
. The select()
function is a way of 3 checking whether data is available on any 2 of a group of file descriptors. It's available 1 on both UNIX and Windows.
Here is a simple example from Beej's Guide to Network Programming.
while(1) { // main accept() loop
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family,
get_in_addr((struct sockaddr *)&their_addr),
s, sizeof s);
printf("server: got connection from %s\n", s);
if (!fork()) { // this is the child process
close(sockfd); // child doesn't need the listener
if (send(new_fd, "Hello, world!", 13, 0) == -1)
perror("send");
close(new_fd);
exit(0);
}
close(new_fd); // parent doesn't need this
}
The child 3 process — after the fork()
— handles the communication 2 asynchronously from accept()
ing further connections 1 in the parent.
Yes, you have the right general idea.
While 10 my C socket programming is a bit rusty, calling 9 accept on a server socket sets up the communications 8 channel back to the client side of the socket. Calling 7 accept on future connection attempts will 6 set up multiple socket channels.
This means 5 that one should take care to not overwrite 4 a single shared structure with a specific 3 connection's data, but it doesn't sound 2 like that's the kind of error you would 1 be prone to make.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.