Trying to write my own simple web server

#define HOST "127.0.0.1" SOCKET Start_Server(short port) { WSADATA wsaData; SOCKET Winsock; struct sockaddr_in Winsock_In; struct hostent *Ip; char hn[1024]; WSAStartup(MAKEWORD(2, 2), &wsaData); Winsock=WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, (unsigned int)NULL, (unsigned int)NULL); if(Winsock == INVALID_SOCKET){ WSACleanup(); return -1; } Ip = gethostbyname(HOST); Winsock_In.sin_port = htons(port); Winsock_In.sin_family = AF_INET; Winsock_In.sin_addr.s_addr = inet_addr(HOST);//inet_addr(inet_ntoa(*((in_addr*)Ip->h_addr_list[0]))); if(bind(Winsock, (SOCKADDR*)&Winsock_In, sizeof(Winsock_In)) == SOCKET_ERROR){ WSACleanup(); return -1; } return Winsock; } void Main_WebServer() { SOCKET Winsock; char Buf[255]; char* temp; char buf[255]; char* buffer[255]; struct sockaddr_in client; int clientsize = sizeof(client); int i; Winsock = Start_Server(5656); listen(Winsock, 5); strcpy(Buf, "HTTP/1.0 200 OK\r\n"); strcat(Buf, "Content-Type: text/html\r\n"); strcat(Buf, "Connection: close\r\n\r\n"); while (1) { int s; FILE *f; s = accept(Winsock, (struct sockaddr*)&client, &clientsize); if (s == INVALID_SOCKET) break; send(s, Buf, (int)strlen(Buf), 0); } closesocket(Winsock); // закрытие сокета WSACleanup(); } 

If you connect via netcat to 5656, then the connection displays headers, which, according to the idea, should be sent to the browser. But when I try to access through the browser localhost: 5656, the browser simply tries to load the page, and will load until I turn off the server. Those. it feels like something is looping around somewhere. Help to understand please.

  • The simplest - Break the connection with the client after sending the desired text. so implemented in the puncture http 1.0 - Alex Kapustin
  • one
    Well done, moving on. one). Check the success of the Start_Server () call. 2). WSACleanup is better not to call at all than twice. There were precedents for some errors associated with this. 3). Consider how you will handle several incoming connections (s = accept (...)) through thread-s or using select (). - avp

1 answer 1

So understandably freezes. The browser cannot find out that the data has run out before it starts. He reads the headers and expects you to send the data now, but you do not. Specify a Content-Length (for example, 0), or use chunked-mode. Or close the socket s yourself after sending the data.

PS: And here's another: what is rn? Simple enough n.

  • one
    PS: And here's another: what is rn? Simple enough n. In general, according to the specification - CRLF. - weekens