简体   繁体   English

recv()未收到预期的字节数

[英]recv() not receiving the number of bytes expected

The issue I'm having right now is regarding: 我现在遇到的问题涉及:

int k = send( hAccepted, p, size, 0 );

'p' is a buffer containing some file, an mp3, text file or what have you. “ p”是一个缓冲区,其中包含一些文件,mp3,文本文件或您所拥有的文件。 The issue is that if the file in question is say '5,000,000' bytes, send() will return 5,000,000 every time it is called, even if the receiving end did not receive all 5,000,000 bytes. 问题是,如果所讨论的文件说的是“ 5,000,000”字节,即使接收端未收到所有5,000,000字节,send()每次调用时都将返回5,000,000。 This is making it quite difficult to debug on the server side, as the client is fully aware it did not receive the whole file, but the server is quite convinced that it sent the whole thing. 这使得在服务器端进行调试非常困难,因为客户端完全知道它没有接收到整个文件,但是服务器非常确信它发送了整个文件。

send() returns the number of bytes transferred to the socket send buffer. send()返回传输到套接字发送缓冲区的字节数。 If it returns 50,000, then 50,000 bytes were transferred. 如果返回50,000,则传输50,000字节。 If you didn't receive them all, the problem is at the receiver, or in the network. 如果您没有全部收到,则问题出在接收器或网络上。

You would have to post some code before any further analysis is possible. 您必须先发布一些代码,然后才能进行进一步的分析。

Probably you're expecting to receive all those bytes in a single recv() call. 可能您希望在一个recv()调用中接收所有这些字节。 It isn't obliged to do that by its specification. 它没有义务按照其规范进行操作。 You have to loop: 您必须循环:

char buffer[8192];
int length = ... // number of bytes expected;
int total = 0;
int count;

while (total < length && (count = recv(socket, buffer, min(sizeof buffer, length-total), 0)) > 0)
{
    write(outfd, buffer, count);  // or do something else with buffer[0..count-1]
    total += count;
}
if (count < 0)
{
    perror("recv");
}

Or else you've done an abortive close at the sender which discards data in flight. 否则,您已经在发送方进行了异常关闭,从而丢弃了正在传输的数据。

Or you got an error during recv() and didn't detect it in your code. 否则,您在recv()期间出错,但未在代码中检测到它。

Or ... 要么 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM