Maggie
Maggie

Reputation: 8071

client/server architecture with multiple clients

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

Answers (2)

Tom
Tom

Reputation: 19304

One basic workflow for this kind of server, if you don't want to use multithreading, is like this:

  • Create an fd_set of file descriptors to watch for reading
  • Open a socket
  • Bind the socket to a port to listen on
  • Start listening on the socket
  • Add the socket's file descriptor to the fd_set
  • While not done
    • Use select to wait until a socket is ready to read from
    • loop through the fds in your fd_set that have data available
    • If the current fd is your listening socket, accept a new connection
    • Else, it's a client fd. Read from it, and perhaps write back to it.

This 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

Eregrith
Eregrith

Reputation: 4367

You should look the man of select. It will tell you when and which sockets are ready to write/read

Upvotes: 1

Related Questions