Reputation: 77
I am programming a real-time networking system in C/C++ with Berkeley C sockets, which works on a tick-based interval. Every tick, the client program will read data from the socket with recvfrom().
The problem is that if the server did not send any data, the client will read the last data that was sent on the socket.
For example the client (pseudocode)
while (true)
{
if (time_to_update())
{
int n = recvfrom(data,...);
printf("%s",data);
}
}
And server:
int main()
{
int m = recvfrom(data,...);
int n = sendto(...,"hello");
}
Then the client would keep printing "hello", whereas I only need it to print it once.
This is qutie similar to this question, recvfrom re-reading data on socket ,but I do not understand the answer very well and it does seem to solve the problem more generally.
I'm guessing the data is stored in a buffer on the netword card, in which case is there a away to clear the buffer after 1 read? Another method I have in mind is to number the packets and only read new ones, but all types are finite so I'm hoping there might be a cleaner way.
How would I make it so the client only reads the received data once?
Upvotes: 2
Views: 2380
Reputation: 310840
printf("%s",data);
Usual problems. Not testing for error; not testing for end of stream; not using the length. Should be:
if (n < 0)
{
perror("recv"); // or better
break;
}
else if (n == 0)
break; // peer has disconnected
else
printf("%.*s", n, data);
If you don't check these things you will spin forever and print garbage when they happen.
I'm guessing the data is stored in a buffer on the netword card
No.
in which case is there a away to clear the buffer after 1 read
Reading it clears it. Your problem lies elsewhere.
Upvotes: 4
Reputation: 10316
Are you checking the returned value in your variable m
? It could very well be returning zero or -1 (so no bytes have been read), and you keep re-printing the same value of data
over and over again because nothing is modifying it.
Upvotes: 3