我有客户端和服务器来传输图像。客户端发送图像二进制文件,服务器接收并存储。我使用buff vector来存储二进制文件。
客户端:
bytes_sent = send(socketfd, &fileSize, sizeof(fileSize), 0);
bytes_sent = send(socketfd, &fileContents[0], fileSize, 0);
服务器端:
bytes_received = recv(new_sd, &temp.imageSize, sizeof(temp.imageSize), 0);
bytes_received = recv(new_sd, &buff[0], buff.size(), 0);
if(bytes_received < 0)
break; //Error
if(bytes_received == 0)
break; //Disconnect
img.write(&buff[8], temp.imageSize);
印刷的bytes_received和bytes_sent,结果: bytes_received = 8 + bytes_sent
。我用vim(或记事本)打开创建的图像,图像开头有/00/00/00/00/00/00/00/00
个额外字符。为了解决这个问题,我已经将buff [0]改为buff [8],现在收到的图像效果很好。
如何在没有这些8/00字符的情况下接收二进制文件?
答案 0 :(得分:0)
传输二进制文件的简便方法是:
示例:
sender:
file = open_file("file_name",read_binary)
while(file.read(bytes)!=null){
send(toreceiver_socket,read_data);
}
file.close()
toreceiver_socket.close()
receiver
file = open_file("file_name",write_binary)
while(sender_socket_not_closed){
data = sendersocket.receive()
file.write()
}
file.close()
我刚刚展示了如何实现这一目标。这将确保成功传输文件。