Reputation: 8071
I need to implement a server/client code in C.
Server needs to be able to accept exactly four connections at the time.
I can't get this working. What I've done so far:
1. create a socket
2. set it to non-blocking: fcntl(sock,F_SETFL, O_NONBLOCK);
3. bind it
4. listen: listen(sock, 4);
The part which I am not quite sure about is how to accept the client's connection. My code looks something like this:
while (1) {
if ((sockfd = accept(sock, (struct sockaddr *) &client_addr, &client_size)) < 0) {
perror("Error\n");
}
read(sockfd, &number, sizeof(number));
write(sockfd, &number, sizeof(number));
}
When I execute client and server code, client seems to be writing something to the socket, which server never receives and the entire execution blocks. What is the proper way to accept connections from multiple clients?
Upvotes: 2
Views: 1575
Reputation: 19304
One basic workflow for this kind of server, if you don't want to use multithreading, is like this:
fd_set
of file descriptors to watch for readingfd_set
select
to wait until a socket is ready to read fromfd_set
that have data availableThis page shows a flowchart of the above process. (Scroll down for a very nicely annotated example.)
This page is chock full of examples for select
.
Upvotes: 2
Reputation: 4367
You should look the man of select
. It will tell you when and which sockets are ready to write/read
Upvotes: 1