Path: utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!thunder.mcrcim.mcgill.edu!mouse From: mouse@thunder.mcrcim.mcgill.edu (der Mouse) Newsgroups: comp.unix.wizards Subject: Re: socket problem? Keywords: socket read Message-ID: <1991May24.062158.26127@thunder.mcrcim.mcgill.edu> Date: 24 May 91 06:21:58 GMT References: <1991May20.210923.12177@rfengr.com> Organization: McGill Research Centre for Intelligent Machines Lines: 48 In article <1991May20.210923.12177@rfengr.com>, briand@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@larry.mcrcim.mcgill.edu