fatrock92
fatrock92

Reputation: 837

TCP/IP polling client send and recv in c

I am making a Chat server and client using tcp/ip in c. I made the server part which threads multiple clients. On client side I have a while loop that can send a line and then wait for the server reply. I want to make client poll both send and recv functions to check if the another client has sent something. This is what I have -

while (1){
    char buffer[BUFLEN];
    memset(buffer, 0, sizeof buffer);
    gets(buffer);
    //sendall(sd, buffer, BUFLEN);
    send(sd, buffer, BUFLEN, 0);
    printf("sent:%s\n",buffer);
    //recvline(sd, buffer, BUFLEN);
    recv(sd, buffer, BUFLEN, 0);
    printf("recieved:%s\n", buffer);
}

How do I poll both send() and recv() at the same time and execute the one that comes first??

Want to do something like this..

if(send(sd, buffer, BUFLEN, 0) == true)
   send something
else if(recv(sd, buffer, BUFLEN, 0) == true)
   receive something

Upvotes: 1

Views: 2309

Answers (1)

Matt Kline
Matt Kline

Reputation: 10507

I believe you're looking for something like select (MSDN Page, man page).

The basics of using it are as follows:

  • Load up fd_set structs with the socket handles you want to check. Load one fd_set with sockets you want to check for new data to receive, one with sockets you want to send on, and optionally, one with sockets you want to check for errors.

  • Call select, passing it pointers to your fd_set structs.

  • When select returns, the set you passed as the second parameter (readfds) only contains the sockets you passed it which have data waiting. You can call recv on them and it will return immediately. The set you passed as the third parameter (writefds) contains sockets which are ready for writing. You can call send on them and it will return immediately.

Upvotes: 2

Related Questions