gpt4 book ai didi

c++ - Recvfrom 重新读取旧数据

转载 作者:太空宇宙 更新时间:2023-11-04 00:46:19 26 4
gpt4 key购买 nike

我正在使用 Berkeley C 套接字使用 C/C++ 编写实时网络系统,该系统以基于滴答的时间间隔工作。每一次 tick,客户端程序都会使用 recvfrom() 从套接字中读取数据。

问题在于,如果服务器没有发送任何数据,客户端将读取在套接字上发送的最后数据。

例如客户端(伪代码)

while (true)
{
if (time_to_update())
{
int n = recvfrom(data,...);
printf("%s",data);
}
}

和服务器:

int main()
{
int m = recvfrom(data,...);
int n = sendto(...,"hello");
}

然后客户端会一直打印“hello”,而我只需要它打印一次。

这与这个问题非常相似,recvfrom re-reading data on socket,但我不太理解答案,它似乎更普遍地解决了问题。

我猜数据存储在网卡的缓冲区中,在这种情况下是否有办法在读取 1 次后清除缓冲区?我想到的另一种方法是对数据包进行编号并只读取新的数据包,但所有类型都是有限的,所以我希望可能有更简洁的方法。

我该怎么做才能让客户端只读取一次接收到的数据?

最佳答案

printf("%s",data);

常见问题。不测试错误;不测试流结束;不使用长度。应该是:

if (n < 0)
{
perror("recv"); // or better
break;
}
else if (n == 0)
break; // peer has disconnected
else
printf("%.*s", n, data);

如果你不检查这些东西,你将永远旋转并在它们发生时打印垃圾。

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

阅读它会清除它。你的问题出在别处。

关于c++ - Recvfrom 重新读取旧数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37545646/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com