我有一个关于从另一个服务器端接收文件并将其发送到客户端的服务器(称为 servera)的问题。问题是客户端收到的文件大小为 0,因此文件的字节数为零:
/* receive file size from serverB */
recv(s,&bytes,sizeof(bytes),0);
/* send file size to client */
send(file_descriptor,&bytes,sizeof(bytes),0);
bytes = ntohs(bytes);
/* receive (from serverb) and send immediately (to client)*/
while (total != bytes) {
nread = read(s,&c,sizeof(char));
if(nread == 1){
send(file_descriptor,&c,sizeof(c),0);
total += nread;
}
}
出了什么问题?
最佳答案
一切都可能是错误的。
在依赖副作用之前,您必须检查 I/O 调用是否有错误,否则您将得到不可预测的结果。
在您的情况下,也许第一个 recv()
失败,使 bytes
未初始化为 0。
此外,一次读取一个字节的循环非常效率低下,并且仍然无法检查它是否设法发送该字节(send()
可能会失败在这种情况下您需要重试)。
关于c - 发送文件套接字C linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17322022/