简体   繁体   中英

Send XML file over socket C++

I'm trying to send a .ui file's content by

std::ifstream f;
f.open(filePath, std::ios::binary | std::ios::ate);
int fileSize = f.tellg();
char *bytes = new char[fileSize];

f.read((char *) bytes, fileSize);

send(clientSocket, std::to_string(fileSize).c_str(), 16, 0);
send(clientSocket, bytes, fileSize, 0);
f.close();
delete [] bytes;

Despite being opened and size of file is counted correctly, on debug, I see

f.read((char *) bytes, fileSize); f: std::ifstream fileSize:2328 bytes: 0x6824b0 "\r\360\255\272 ...

The sequence

\r\360\255\272

repeats further and eventually ends with

\r\360\255\272\253\253\253\253\253\253\253\253\253\253\253\253\253\253\253\253\356\376\356\376\356\376", <incomplete sequence \356\376>

How to correctly pass and receive any xml content over WinSock2_32 ?

You are not seeking the file stream back to position 0 before reading the bytes, so f.read() will fail. Add a call to f.seekg(0) beforehand.

Also, you should send the fileSize in binary format, not as a string, especially since the string is NOT 16 bytes in length.

Try this:

std::ifstream f(filePath, std::ios::binary | std::ios::ate);
if (!f.is_open()) ...

int fileSize = f.tellg();
if (fileSize < 0) ...

char *bytes = new char[fileSize];
f.seekg(0);
f.read(bytes, fileSize);

int32_t tmp = htonl(fileSize);
send(clientSocket, &tmp, sizeof(tmp), 0);
send(clientSocket, bytes, fileSize, 0);

delete [] bytes;
f.close();

If you absolutely need to send the fileSize as a 16-character string, use a formatted char[] buffer for that, eg:

std::ifstream f(filePath, std::ios::binary | std::ios::ate);
if (!f.is_open()) ...

int fileSize = f.tellg();
if (fileSize < 0) ...

char *bytes = new char[fileSize];
f.seekg(0);
f.read(bytes, fileSize);

char s_fileSize[17] = {};
sprintf(s_fileSize, "%0.16d", fileSize);

send(clientSocket, s_fileSize, 16, 0);
send(clientSocket, bytes, fileSize, 0);

delete [] bytes;
f.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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