I'm trying to write a minimal HTTP server on Windows and see the response in Chrome with http://127.0.0.1/5000. The following code works sometimes ("Hello World"), but the request fails half of the time with ERR_CONNECTION_ABORTED
in Chrome (even after I restart the server). Why?
Error:
#include <winsock2.h>
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
int main()
{
WSADATA WSAData;
SOCKET sock, csock;
SOCKADDR_IN sin, csin;
WSAStartup(MAKEWORD(2,0), &WSAData);
sock = socket(AF_INET, SOCK_STREAM, 0);
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_family = AF_INET;
sin.sin_port = htons(5000);
bind(sock, (SOCKADDR *) &sin, sizeof(sin));
listen(sock, 0);
while(1)
{
int sinsize = sizeof(csin);
if((csock = accept(sock, (SOCKADDR *) &csin, &sinsize)) != INVALID_SOCKET)
{
std::string response = "HTTP/1.1 200 OK\nConnection: close\nContent-Length: 11\n\nHello World";
send(csock, response.c_str(), response.size(), 0);
std::cout << "done";
closesocket(csock);
}
}
return 0;
}