Search code examples
cwinsock

Winsock send function waits indefinitely


In this code, send function doesn't block but doesn't send either. If I call shutdown , then it is forced to send.

How do I make this code send a small message within a second or so?

This code is suppose to respond to web browser GET request. (User types localhost:27015) It is just a test, I do not need it for work or a bigger project.

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <stdio.h>

#pragma comment(lib, "Ws2_32.lib")


int main(int argc, wchar_t* argv[]) {

WSADATA wsaData;
int iResult = 0;

SOCKET ListenSocket = INVALID_SOCKET;
sockaddr_in service;

iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); 

ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr("127.0.0.1");
service.sin_port = htons(27015);

iResult = bind(ListenSocket, (SOCKADDR *)& service, sizeof(service));

listen(ListenSocket, SOMAXCONN);

auto AcceptSocket = accept(ListenSocket, NULL, NULL);

char getbuf[400];

recv(AcceptSocket, getbuf, 400, NULL);
getbuf[399] = '\0';

printf("%s",getbuf);

char str[] = "HTTP/1.1 200 OK\r\n"
"Date: Sun, 19 May 2018 08 : 56 : 53 GMT\r\n"
"Server : Apache / 2.2.14 (Win32)\r\n"
"Last - Modified : Sat, 20 Nov 2004 07 : 16 : 26 GMT\r\n"
"ETag : \"10000000565a5-2c-3e94b66c2e680\" \r\n"
"Accept - Ranges : bytes\r\n"
"Content - Length : 44\r\n"
"Connection : close\r\n"
"Content - Type : text / html\r\n"
"X - Pad : avoid browser bug\r\n\r\n"

"<html><body><h1>It works!</h1> </body> </html>\r\n\0";


char *sendbuf = (char*)str;
iResult = send(AcceptSocket, sendbuf, (int)strlen(str), 0);

//shutdown(AcceptSocket, SD_BOTH); //forces to send

while (1);
return 0;
}

Solution

  • char str[] = 
    "HTTP/1.1 200 OK\r\n"
    "Date: Sun, 19 May 2018 08:56:53 GMT\r\n"
    "Server: Apache/2.2.14 (Win32)\r\n"
    "Last-Modified: Sat, 20 Nov 2004 07:16:26 GMT\r\n"
    "ETag: \"10000000565a5-2c-3e94b66c2e680\"\r\n"
    "Accept-Ranges: bytes\r\n"
    "Content-Length: 46\r\n"
    "Connection: close\r\n"
    "Content-Type: text/html\r\n"
    "X-Pad: avoid browser bug\r\n\r\n"
    "<html><body><h1>It works!</h1></body></html>\r\n";
    

    The browser isn't a person, it doesn't know what the hell is Content - Type :, it doesn't recognize 08 : 56 : 53 as a valid time, there is no MIME type called text / html. Stop putting spaces where there shouldn't be any, the browser doesn't have a brain, it can't guess.

    Also you are explicitly telling the connection will close after the data is sent, with the header Connection: close, but you are not doing that. If you intent to keep the connection alive, then use Connection: keep-alive.

    Moreover, your data is not 44 bytes in length.