循环时recv()函数如何工作?

use*_*966 6 c sockets client-server recv server

我在 MSDN 中读到有关 send() 和 receive() 函数的内容,有一点我不确定我是否理解。

例如,如果我发送一个大小为 256 的缓冲区,并接收前 5 个字节,那么下次我调用 recv() 函数时,它将指向第 6 个字节并从那里获取数据?

例如 :

char buff[256];
memcpy(buff,"hello world",12);
send(sockfd, buffer, 100) //sending 100 bytes

//server side:
char buff[256];
recv(sockfd, buff, 5) // now buffer contains : "Hello"?
recv(socfd, buff,5) // now I ovveride the data and the buffer contains "World"?
Run Code Online (Sandbox Code Playgroud)

谢谢!

use*_*421 8

在C中从TCP循环接收到缓冲区的正确方法如下:

char buffer[8192]; // or whatever you like, but best to keep it large
int count = 0;
int total = 0;

while ((count = recv(socket, &buffer[total], sizeof buffer - total, 0)) > 0)
{
    total += count;
    // At this point the buffer is valid from 0..total-1, if that's enough then process it and break, otherwise continue
}
if (count == -1)
{
    perror("recv");
}
else if (count == 0)
{
    // EOS on the socket: close it, exit the thread, etc.
}
Run Code Online (Sandbox Code Playgroud)

  • 我知道这很旧,但我认为应该是:`while ((count = recv(socket, &buffer[total], sizeof (buffer) - Total, 0)) > 0) {` (4认同)