C Board  

Go Back   C Board > General Programming Boards > Networking/Device Communication

Reply
 
LinkBack Thread Tools Display Modes
Old 09-11-2009, 11:18 PM   #1
Registered User
 
Join Date: Sep 2009
Posts: 11
Question abt read(fd, buffer, 1024)

This is some of my code, what I want to do is keep trying to read
information from my server until it gives me a response. But is
this a correct way of doing it? or will it cause me problems? Cos if the
server gives me the wrong message then i'm going to exit otherwise I'll
process the response. So after this code I process "buffer" to determine
my course of action.

Code:
//
	write(nsFD,lookUp, strlen(lookUp));
	
	//Iterate until a response is returned
	while((numBytesRead = read(nsFD, buffer, 1024) < 0)) {
	
                 }

Cheers
tesla is offline   Reply With Quote
Old 09-12-2009, 03:52 AM   #2
Registered User
 
Join Date: Oct 2008
Posts: 452
No. read() will return:
- -1 on error (look at the available errno's; some you might want to ignore and loop until you get a different result. For instance EINTR is quite useless there).
- 0 on disconnect
- Otherwise the number of bytes received.
Note that read, when the socket blocks, will not return at all until it has data (or an error or end of file). So there's no reason to loop until you get anything: it only returns when you get anything.

Your program might contain another bug that a lot of programs have and actually is ignored by most coders. If the socket is TCP, this protocol is stream based. That means that the server, if it wants to send 2 bytes, might only send 1 byte first (theoretically, although in practice I've never seen it happen). So read() might return only one byte even though the server sent two. So if you expect more bytes, keep reading until you have as much as you expect.
EVOEx is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Quick C Question - checking buffer for input sean C Programming 3 11-13-2004 12:23 PM
Question for network programmers rtunez33 Tech Board 6 10-06-2004 10:06 AM
question abt getline kashifk C++ Programming 1 09-18-2003 07:50 PM
Simple Buffer Overflow Question Black-Hearted C++ Programming 26 06-15-2003 02:51 PM
what does this warningmean??? kreyes C Programming 5 03-04-2002 07:53 AM


All times are GMT -6. The time now is 08:33 AM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.0 RC2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22