1

我有一个用 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,或者如果它完全收到,为什么从浏览器看不到?

4

2 回答 2

0

您的缓冲区大小仅为 512 字节,但您发送的 tmp.length() * 5 根据我的计算 = 1040。所以 write 将读取缓冲区的末尾,导致坏事发生。

此外,您应该使用 strncpy 而不是 memcpy,因为 strncpy 将包含尾随空值,而您的 memcpy 将排除空值并保留缓冲区原样,这意味着它可能会在其中放置任何内容,从而导致您的输出为随机的。

于 2013-04-04T09:13:24.220 回答
0

我解决了!它是在解析和替换之前设置的内容长度。解析后,字符串的长度发生了变化,但内容长度保持不变。傻我!

于 2013-04-04T10:05:25.743 回答