我有一个用 C++ 编写的 HTTP 服务器。在某些时候,我想处理一个必须作为响应发送给客户端的 html 文件,并将一些预定义的标签替换为其他标签。过程如下:
do {
size = read(page_fd, buffer, 1024);
/* processing buffer - replacing variables */
std::string tmp = std::string(buffer);
unsigned int start = 0, end;
do {
start = tmp.find("#{", start);
if (start != std::string::npos && start < tmp.length()) {
end = tmp.find("}", start + 1);
if (end != std::string::npos && end < tmp.length()) {
std::string tmp2 = tmp.substr(start + 2, end - start - 2);
tmp = tmp.replace(start, end - start + 1, params[tmp2.c_str()]);
start = end + 1;
}
}
} while (start != std::string::npos && start > end && start < tmp.length());
char buff[512];
memcpy(buff, tmp.c_str(), tmp.length());
std::cout << buff << "\n\n";
/* end of processing - writing to socket */
write(_conn_fd, buff, tmp.length());
} while (size > 0);
我要发送给客户端的 html 页面是这样的:
<html>
<head>
<title>Index</title>
</head>
<body>
<h1>It works!</h1>
<h2>#{custom}</h2>
<p>This page was served through a C++ HTTP server!</p>
</body>
</html>
检查客户端收到的内容时,html代码总是不完整的,如下:
<html>
<head>
<title>Index</title>
</head>
<body>
<h1>It works!</h1>
<h2>replaced message</h2>
<p>This page was served through a C++ HTTP server!</p>
代码中的std::cout
行输出正确的 html 字符串。
为什么客户端没有收到完整的 html,或者如果它完全收到,为什么从浏览器看不到?