socket problem?

der Mouse mouse at thunder.mcrcim.mcgill.edu
Fri May 24 16:21:58 AEST 1991


In article <1991May20.210923.12177 at rfengr.com>, briand at rfengr.com (Brian Dear) writes:

> Question about sockets.  I've got a simple server program [...].
> That all works fine.

> It's the client side that's got a bug.  It sets up its socket with
> the server successfully, connect()'s successfully, etc.  Sends out
> its 'r' successfully (cuz the server gets it and sends out its
> struct) but the client's read() never works.  The client has a read()
> function such as this

> 	read( sd, &theStruct, sizeof(theStruct) );

Danger, danger.  read() on a socket - indeed, I think on anything but a
plain file - does not necessarily read as many bytes as asked for.  It
can read anywhere from one byte to the full amount (even zero bytes,
but only if the socket is marked non-blocking or if the other end has
been shut down).

You have to keep calling read until you get an error, EOF, or
everything you're looking for.  Something like

int Read(fd,buf,nb)
int fd;
char *buf;
int nb;
{
 int left;
 char *bp;
 int nr;

 left = nb;
 bp = buf;
 while (left > 0)
  { nr = read(fd,bp,left);
    if (nr < 0) return(-1);
    if (nr == 0) return(nb-left);
    left -= nr;
    bp += nr;
  }
 return(nb);
}

					der Mouse

			old: mcgill-vision!mouse
			new: mouse at larry.mcrcim.mcgill.edu



More information about the Comp.unix.wizards mailing list