flushing a socket

flushing a socket

Post by e.. » Sat, 16 Oct 1999 04:00:00



I needed a function to flush the incoming data buffer for a TCP socket
and wrote the function below.  The problem is that when I kill the
server that the socket is connected to while flushing the buffer, recv()
doesn't return an error; it reads data from the socket infinitely.
And select() still reports the socket as ready to read from (I know
an error pending will cause this correct behavior though, but how do
I tell the difference between data ready or socket error?)  Can anyone
help me with this?  Is there a better approach to flushing the socket
buffer than the way I'm doing it here?  Thanks for any help.  -ekw

int tcpFlush(int socket)
{
   fd_set rset;
   struct timeval timeout;
   int done;
   int status;
   char byte;

   timeout.tv_sec=0;
   timeout.tv_usec=0;

   done=FALSE;
   while(!done)
   {
      FD_ZERO(&rset);
      FD_SET(socket, &rset);

      select(socket+1, &rset, NULL, NULL, &timeout);

      if(FD_ISSET(socket, &rset))
      {
          if( (status=recv(socket, &byte, 1, 0)) == -1)
               return(ERROR);
      }
      else
          done=TRUE;
   }
   return(OK);

Quote:}

Sent via Deja.com http://www.deja.com/
Before you buy.
 
 
 

flushing a socket

Post by Joe Halpi » Sat, 16 Oct 1999 04:00:00



> I needed a function to flush the incoming data buffer for a TCP socket
> and wrote the function below.  The problem is that when I kill the
> server that the socket is connected to while flushing the buffer, recv()
> doesn't return an error; it reads data from the socket infinitely.
> And select() still reports the socket as ready to read from (I know
> an error pending will cause this correct behavior though, but how do
> I tell the difference between data ready or socket error?)  Can anyone
> help me with this?  Is there a better approach to flushing the socket
> buffer than the way I'm doing it here?  Thanks for any help.  -ekw
>       if(FD_ISSET(socket, &rset))
>       {
>           if( (status=recv(socket, &byte, 1, 0)) == -1)
>                return(ERROR);
>       }

When the connection has been broken, and there is no more data pending
in the system buffers, recv() will return 0, which isn't being checked
for here. Check for that and break out of the loop when you get it.

When select() tells you that the socket is active, what that means is
that a read on it won't block. This is true of a socket at EOF as well
as one with data ready.

Joe