Threaded server sending messages between clients

I am writing a C network server that combines two clients and allows them to send messages to each other.

At the moment, each client has its own thread on the server, and in the thread I have a loop, which is basically while((numBytesRead = read(fd, buffer, 1024)) > 0). This works great, and I can receive messages and then send them back to the client.

My problem is that I'm not sure what the best way to send messages from one client to another is through the server.

I think my biggest problem is that there are blocks read(), so I won’t be able to send a message to the client until the client sends some text to the server so that the reading stops blocking.

Is there any way around this? My initial thought was to make one thread read from the client and one write to the client, but if the read is blocked in the same thread and then I try to write to the same file descriptor, then this will not cause a problem?

Appreciate any help !! :)

+3
source share
3 answers

readonly blocks the flow of the client, which does not send data; so you can theoretically use a client thread that just sent data to writeanother.

, ( ), . , ( ) .

, , - select, , ; - ( , ). :

  • (-, 100 )
  • :
  • :
+2

, ,

  • ""
  • uniq
  • "" (), " "
  • ()

- .

+1

- . . kqueue (FreeBSD) epoll (Linux), - (AIO)

So, if select () is a choice, you can use the following approach (just an example, something like pseudocode):

fd_set read_set, write_set;
struct timeval timeout;

while(!quit)
{
     // adds your sockets to fd_set structure, return max socket + 1, this is important! 
     max = fillFDSet(&read_set); 
     setReadTimeout(&timeout); // sets timeout for select

     if (0 < select(max, &read_set, NULL, NULL, &timeout)) // wait for read
     {
           // there is at least one descriptor ready
           if (FD_ISSET(your_socket))
           {
               socket_size = read(socket, socket_buffer, 1024);
           }
     }
     max = fillFDSet(&write_set); 
     setWriteTimeout(&timeout); // sets timeout for select

     if (0 < select(max, NULL, &write_set, NULL, &timeout)) // wait for write
     {
           // there is at least one descriptor ready
           if (FD_ISSET(your_socket))
           {
               write(socket, socket_buffer, socket_size);
           }
     }
}
0
source

All Articles