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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With