簡體   English   中英

通過套接字 C++ 發送 XML 文件

[英]Send XML file over socket C++

我正在嘗試通過以下方式發送.ui文件的內容

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;

盡管已打開並且文件大小計算正確,但在調試時,我看到了

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

序列

\r\360\255\272

進一步重復並最終以

\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", <不完整序列 \356\376>

如何通過WinSock2_32正確傳遞和接收任何 xml 內容?

在讀取字節之前,您沒有將文件 stream 重新搜索到 position 0 ,因此f.read()將失敗。 事先添加對f.seekg(0)的調用。

此外,您應該以二進制格式發送fileSize ,而不是作為字符串,特別是因為字符串的長度不是 16 個字節。

嘗試這個:

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();

如果您絕對需要將fileSize作為 16 個字符的字符串發送,請為此使用格式化的char[]緩沖區,例如:

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM