【问题标题】:C++ - Simple server which sends simple HTML to clientsC++ - 向客户端发送简单 HTML 的简单服务器
【发布时间】:2010-10-26 19:34:56
【问题描述】:

现在,我只是在玩这个,我不确定为什么这不起作用。

#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
#include <cassert>

const char html[] = "HTTP/1.1 200 OK\r\n"
"Connection: close\r\n"
"Content-type: text/html\r\n"
"\r\n"
"<html>\r\n"
"<head>\r\n"
"<title>Hello, world!</title>\r\n"
"</head>\r\n"
"<body>\r\n"
"<h1>Hello, world!</h1>\r\n"
"</body>\r\n"
"</html>\r\n\r\n";

int main() {
    WSADATA wsa;

    assert( WSAStartup( MAKEWORD( 2, 2 ), &wsa ) == 0 );

    addrinfo *res = NULL;
    addrinfo hints;

    ZeroMemory( &hints, sizeof( hints ) );

    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    assert( getaddrinfo( NULL, "80", &hints, &res ) == 0 );

    SOCKET s = socket( res->ai_family, res->ai_socktype, res->ai_protocol );

    assert( s != INVALID_SOCKET );
    assert( bind( s, res->ai_addr, (int)res->ai_addrlen ) != SOCKET_ERROR );
    assert( listen( s, SOMAXCONN ) != SOCKET_ERROR );

    SOCKET client = accept( s, NULL, NULL );

    assert( client != INVALID_SOCKET );

    char buffer[512];
    int bytes;

    bytes = recv( client, buffer, 512, 0 );

    for ( int i = 0; i < bytes; ++i ) {
        std::cout << buffer[i];
    }

    assert( send( client, html, strlen( html ) - 1, 0 ) > 0 );
    assert( shutdown( client, SD_BOTH ) != SOCKET_ERROR );

    closesocket( client );
    WSACleanup();

    return 0;
}

当我编译并运行它,然后在浏览器中导航到 127.0.0.1 时,我会在控制台中看到它:

GET / HTTP/1.1

主机:127.0.0.1

连接:保持活动

用户代理:Mozilla/5.0(Windows;U;Windows NT 5.1;en-US)AppleWebKit/530.5(K HTML,如 Gecko)Chrome/2.0.172.8 Safari/530.5

缓存控制:max-age=0

接受:application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,/;q=0.5

接受编码:gzip,deflate,bzip2,sdch

接受语言:en-US,en;q=0.8

接受字符集:ISO-8859-1,utf-8;q=0.7,*;q=0.3

EDIT - 我已经更新了我发送的 HTML。我刚刚用 Mozilla Firefox 和 Google Chrome 测试了它,它可以在 Firefox 中运行,但不能在 Chrome 中运行!

EDIT 2 - 所以看起来它在 Firefox 上运行的原因,而不是 Chrome,是因为 Firefox 将 HTML 显示为接收到的 HTML,而 Chrome 等待连接关闭,然后再执行任何操作渲染。我添加了关闭套接字的代码并且它起作用了。我已经用工作源更新了我的代码。

【问题讨论】:

    标签: c++ html http winsock2


    【解决方案1】:

    您需要发回状态行:

    HTTP/1.1 200 正常

    在您的响应标头之前。

    请参阅 Fiddler (www.fiddler2.com) 以更好地了解正确的 HTTP 响应是什么样的。

    关于您以后的编辑,所有浏览器在开始渲染之前都会等待一定量的数据; Chrome 的限制与 Firefox 的不同。如果您设置了 Content-Length 或使用 HTTP Chunked 编码,您会看到正确的行为。

    【讨论】:

      【解决方案2】:

      看猫鼬http://code.google.com/p/mongoose/ 它是一个自包含的库,它是一个多线程的 http web 服务器,并且有一个超级简单的 api(尚未完成)。在几分钟内,我就能够将它绑定到我已经存在的应用程序。

      我今天早些时候也有同样的问题(给我的 C++ 应用程序一个 Web 端)Giving C++ Application a HTTP Web Server Functionality

      【讨论】:

      猜你喜欢
      • 2015-12-29
      • 2012-04-28
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      相关资源
      最近更新 更多