Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know when the socket has finished reading

Tags:

c

sockets

I know little about sockets but so far I haven't had much of a problem. I'm actually stuck on how to know when the other side finished sending msgs. What I have so far is a while loop on the server side which reads from the socket 'til has nothing left (or that is what is supposed to do). This is the code:

char c[1024]; //buffer
inst much;
while(much = read(sockfd, &c, 1024) > 0) {
   printf("read %d, clientSays> %s\n", much, c);
}
printf("reading, finished\n");

So, on the client side, I send a "hello world" message which is actually display on the server console, but it doesn't print the "reading finishes" message so I suppose that it gets stuck waiting for another message.

I though that the read function would return 0 when there was nothing else to read, but I guess that's not the case

So, what am I doing wrong?


Update

Actually, after reading your answers and going through the code a little bit, I realized that that's what protocols are for.

I should know before hand when one side has finished sent and when the other side should start writing. Maybe adding a last char to let know that I finished sending, or a prefixed size for the message.

Thanks for your answers.

like image 947
gvalero87 Avatar asked Nov 09 '10 02:11

gvalero87


2 Answers

Your sample expects read() to return 0, which will happen when client close connection. If you have to keep connection open but know where the end of the message is, you can either prefix each message with its length or add an end of message marker at the end. There is nothing built in into the sockets API to assist you.

like image 101
cababunga Avatar answered Oct 31 '22 01:10

cababunga


I know this is a kinda sad/inefficient way to do it, but back in the day I used a char delimiter to know when to stop reading a socket.

Covers head with hands

like image 23
Ben Avatar answered Oct 31 '22 03:10

Ben