Search code examples
c++csocketsrecvfrom

Recvfrom re-reading old data


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?


Solution

  • 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.