[英]C++ Send a file containing \0 via sockets without accidental closure
I serialize the file via the code beneath, and send it over winsocks, this works fine with textfiles, but when I tried to send a jpg, the string contains \\0 as some of the character elements, so the sockets only send part of the string, thinking \\0 is the end, i was considering replacing \\0 with something else, but say i replace it with 'xx', then replace it back on the other end, what if the file had natural occurrences of 'xx' that get lost? 我通过下面的代码序列化文件,然后通过winsocks发送它,这对于文本文件可以正常工作,但是当我尝试发送jpg时,字符串包含\\ 0作为某些字符元素,因此套接字仅发送部分字符串,认为\\ 0是结尾,我正在考虑用其他方式替换\\ 0,但是说我用'xx'替换了它,然后又在另一端替换了它,如果文件中自然出现了'xx'怎么办走开? Sure I could make a large, unlikely sequence, but that bloats the file. 当然,我可以制作一个大的,不太可能的序列,但这会使文件膨胀。
Any help appreciated. 任何帮助表示赞赏。
char* read_file(string path, int& len)
{
std::ifstream infile(path);
infile.seekg(0, infile.end);
size_t length = infile.tellg();
infile.seekg(0, infile.beg);
len = length;
char* buffer = new char[len]();
infile.read(buffer, length);
return buffer;
}
string load_to_buffer(string file)
{
char* img;
int ln;
img = read_file(file, ln);
string s = "";
for (int i = 1; i <= ln; i++){
char c = *(img + i);
s += c;
}
return s;
}
Probably somewhere in your code (that isn't seen in the code you have posted) you use strlen()
or std::string::length()
to send the data, and/or you use std::string::c_str()
to get the buffer. 可能在代码中的某处(在您发布的代码中未看到),您使用strlen()
或std::string::length()
发送数据,和/或使用std::string::c_str()
获取缓冲区。 This results in truncated data because these functions stop at \\0. 由于这些函数在\\ 0处停止,因此将导致数据被截断。
std::string is not good to handle binary data. std :: string不适合处理二进制数据。 Use std::vector<char>
instead, and remove the new[] stuff. 使用std::vector<char>
代替,并删除new []内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.