std::ifstream file(localPath.c_str(), std::ifstream::binary);
file.seekg(0, std::ifstream::beg);
while(file.tellg() != -1)
{
char *p = new char[1024];
bzero(p, 1024);
file.read(p, 1024);
printf("%ld\n", file.gcount());
n = send(fd, p, strlen(p), 0);
if (n < 0) {
error("ERROR writing to socket");
} else {
printf("---------%d\n", n);
}
delete p;
}
file.close();
实际上我要发送的图像是 png(大小:27892 字节)就读取而言,每个字节都被正确读取。但是,在将它们写入套接字时,只写入了几个字节。在这方面需要帮助。
提前致谢。 :)
最佳答案
strlen()
需要一个以 NULL
结尾的字符串,而不是二进制图像数据,当您使用 strlen()
时,它会在第一个 NULL
(或零)字节,图像数据可能在第一个或第二个字节或任何地方包含零,因此您不能使用 strlen()
来查找图像缓冲区。您应该改用缓冲区大小:
n = send(fd, p, 1024, 0);
关于c++ - 在 C++ 中通过套接字发送图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13250354/