今、私はこれをいじっているだけで、なぜこれが機能しないのかわかりません。
#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 (Gecko のような K HTML) 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
Accept-Encoding: gzip、deflate、bzip2、sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
編集- 送信する HTML を更新しました。これを Mozilla Firefox と Google Chrome でテストしたところ、Firefox では動作しますが、Chrome では動作しません!
編集 2 - Chrome ではなく Firefox で動作していた理由は、Chrome がレンダリングを行う前に接続が閉じるのを待っている間に、Firefox が HTML を受信したとおりに表示するためだったようです。ソケットを閉じるコードを追加したところ、うまくいきました。コードを作業ソースで更新しました。