使用的套接字:udp
我有一个发送 5000 字节的客户端和一个使用此代码的服务器:
客户端代码:
cod = sendto (sFd, (void *) buffer, 5000, 0, (struct sockaddr *)
&soc, sizeof (struct sockaddr_in));
服务器代码:
//leghtBuffer = 5000
while (lenghtBuffer > 0 )
{
//I will insert a signal if pass more than 30 s ...
cod = recvfrom (sFd, buffer,256 , 0, (struct sockaddr *) &clientSoc, &lungimeSocket);
printf("Am received %d bytes " ,cod );
lenghtBuffer = lenghtBuffer - cod;
}
我如何从中读取超过 1 次 256 字节(仍在使用 Udp 套接字)?
最佳答案
UDP 是一种基于消息(数据报)的传输协议(protocol),而不是像 TCP 那样基于流。每个 sendto/recvfrom 都根据完整的消息工作。
在发送端,每次调用 sendto() 都会创建一个指定大小和数据的数据报,在您的例子中是 5000 字节。
在接收端,每次调用 recvfrom() 都会复制接收缓冲区中的下一条消息。由于您的数据报为 5000 字节,但您只提供了 256 字节的缓冲区,因此您的数据报在复制时被截断为 256 字节。
recvfrom() OpenGroup规范阐明了这种情况下的行为:
For message-based sockets such as SOCK_DGRAM and SOCK_SEQPACKET, the entire message must be read in a single operation. If a message is too long to fit in the supplied buffer, and MSG_PEEK is not set in the flags argument, the excess bytes are discarded.
您需要将接收端的缓冲区增加到 5000 字节以容纳整个数据报
关于c - Udp readfrom直到结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29297975/