Recv returns old data
This loop should take data from the socket line by line and put it into a buffer. For some reason, when there is no new data to return, recv returns the last couple of rows it received. I was able to stop the error by commenting out the first recv, but then I can't tell how long the next line will be. I know it is not
while(this->connected){
memset(buf, '\0', sizeof(buf));
recv(this->sock, buf, sizeof(buf), MSG_PEEK); //get length of next message
ptr = strstr(buf, "\r\n");
if (ptr == NULL) continue;
err = recv(this->sock, buf, (ptr-buf), NULL); //get next message
printf("--%db\n%s\n", err, buf);
tok[0] = strtok(buf, " ");
for(i=1;tok[i-1]!=NULL;i++) tok[i] = strtok(NULL, " ");
//do more stuff
}
a source to share
The manual states:
MSG_PEEK This flag causes the receive operation to return data from the head of the receive queue without removing the data from the queue. Thus, subsequent return the same data.
So, I think you are getting the correct behavior, but perhaps expecting something else.
a source to share
Your problem is that when using recv with MSG_PEEK you are giving recv the entire size of your buffer, if there are two strings that already exist like "HELLO \ r \ nHELLO \ r \ n" they will read them into your buff.
ptr will point to the first \ r \ n, then you call recv with (ptr - buff), which will make recv read only the first HELLO, in buf, but since you are already reading this information in buff, you will process two but leaving \ r \ nHELLO \ r \ n in your queue because you haven't read them completely.
Next time, you will look into it and get information about what you have already processed, which made you believe that you are getting duplicate data.
(I hope I wrote this clearly enough, this is a very confusing error you got there :)
a source to share
Hi I am finding a solution:
void receiver(int accepted_client) {
// Ready to receive data from client.
while (true) {
char buffer[256];
recv(accepted_client, &buffer, 255, 0);
int sum = 0;
for (int i = 0; i < 256; i++) // Check that buffer value is zero or not.
sum |= buffer[i];
if (sum != 0) {// If buffer value is not zero then start to print the new received message.
string string_message(buffer);
cout << string_message << endl;
}
memset(&buffer, 0, 256); // Clear the buffer.
}
}
a source to share