#include <iostream>
#include <sstream>
#include <string>
#include <WinSock2.h>
#include <WS2tcpip.h>
int main()
{
int sock, listener;
struct sockaddr_in addr;
char buf[1024];
int bytes_read;
listener = socket(AF_INET, SOCK_STREAM, 0);
if (listener < 0)
{
perror("socket");
exit(1);
}
addr.sin_family = AF_INET;
addr.sin_port = htons(8000);
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (bind(listener, (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
perror("bind");
exit(2);
}
listen(listener, 1);
sock = accept(listener, NULL, NULL);
if (sock < 0)
{
perror("accept");
exit(3);
}
bytes_read = recv(sock, buf, 1024, 0);
//////////////////////////////
std::stringstream response;
std::stringstream response_body;
buf[bytes_read] = '\0';
response_body << "<title>Test C++ HTTP Server</title>\n"
<< "<h1>Test page</h1>\n"
<< "<p>This is body of the test page...</p>\n"
<< "<h2>Request headers</h2>\n"
<< "<pre>" << buf << "</pre>\n"
<< "<em><small>Test C++ Http Server</small></em>\n";
response << "HTTP/1.1 200 OK\r\n"
<< "Version: HTTP/1.1\r\n"
<< "Content-Type: text/html; charset=utf-8\r\n"
<< "Content-Length: " << response_body.str().length()
<< "\r\n\r\n"
<< response_body.str();
bytes_read = send(sock, response.str().c_str(),
response.str().length(), 0);
int close(sock);
return 0;
}