Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!think.com!zaphod.mps.ohio-state.edu!wuarchive!udel!princeton!phoenix.Princeton.EDU!subbarao From: subbarao@phoenix.Princeton.EDU (Kartik Subbarao) Newsgroups: comp.unix.wizards Subject: Re: socket problem? Message-ID: Date: 21 May 91 14:25:39 GMT References: <1991May20.210923.12177@rfengr.com> Sender: news@idunno.Princeton.EDU Reply-To: subbarao@phoenix.Princeton.EDU (Kartik Subbarao) Organization: American Chemical Society Lines: 44 In article <1991May20.210923.12177@rfengr.com> brian@coconut.com writes: > >Question about sockets. I've got a simple server program that runs in the >background. It sits in an infinite loop, with an accept() call, waiting >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) ); > >where sd is the socket descriptor and theStruct is just some big structure. >Read returns a value of 3 or it just blocks altogether. Any ideas? This is not a "bug", but rather a documented feature of sockets. reads and writes are not guaranteed to transfer exactly the amount of data that you request to be sent. Therefore, in doing I/O on sockets, its safer to make sread() and swrite() functions that read until either all the requested data is read/written, or -1 or 0 is returned. Here's what I use: int sread(int s, char *buf, int n) { int save = n; int tmp; /* number of chars read this call */ while (n) { if ((tmp = read(s, buf, n)) <= 0) return tmp ? tmp : save-n; n -= tmp; buf += tmp; } return save; } swrite() is exactly the same thing, replace the read(...) with write(...); -Kartik -- internet% ypwhich subbarao@phoenix.Princeton.EDU -| Internet kartik@silvertone.Princeton.EDU (NeXT mail) SUBBARAO@PUCC.BITNET - Bitnet