[RESOLVED] Read returns 0 or -1 (while data are present)
Hello everybody,
I'm not a socket expert but I have some experience with serial ports I/O under linux...
I am working on client/server project for a home-brew protocol. There was a previous implementation of the client and the server but I have to make a cleaner one. We use the BSD sockets.
On the client side I have to send a message (which is OK) and then wait for the header of the response. The header is a 16 bytes structures.
I use select to wait for data. select returns 1 indicating that there is data to read... However, read() always returns -1 or 0.
I have absolutely no idea of what is going on... Any help would be appreciated.
To read the header I use the code ("header" is the variable where I want to put the header; its a struct with the right fields and HEADER_SIZE is the size of such structure i.e. 16 bytes):
Code:
uint8_t *rcvptr, *buffer = (uint8_t *)header;
size_t to_read=HEADER_SIZE, total_read=0;
ssize_t n_read;
/* Wait for response */
FD_ZERO(&readfds);
FD_SET(fd, &readfds);
readyfds = readfds;
rcvptr = buffer;
while (to_read) {
ready = select(FD_SETSIZE, &readyfds, NULL, NULL, NULL);
fprintf(stderr, "ready=%d\n", ready);
if (ready < 0) { /* select returned an error */
if (errno!=EINTR) { /* this is not an interruption */
perror("read_header");
return READ_MESSAGE_FAIL;
} else {
continue;
}
}
if (ready == 0) { /* select timed out */
return READ_MESSAGE_FAIL;
}
/* We can read in the buffer */
if (FD_ISSET(fd, &readfds)) {
fprintf(stderr, "read=to_read=%zu\n", to_read);
n_read = read(fd, rcvptr, to_read);
fprintf(stderr, "read=n_read=%zd\n", n_read);
if (n_read < 0) {
perror("read_header");
return READ_MESSAGE_FAIL;
}
rcvptr += n_read;
total_read += (size_t)n_read;
to_read -= n_read;
}
}
I have realized that there is a nasty bug in my code (I don't send enough data to the server). I can't test now (it's too late) but I will keep you informed later...
Last edited by duboism; April 15th, 2010 at 03:24 PM.
Reason: Hey, hey a bug in a but
After some intense hacking my colleagues and I realized that we misunderstood the protocol... In fact the server was replying on another port! This seems a rather strange design...
Bookmarks