Mini HTTP Server : http://blog.daum.net/aswip/3863458
HTTP에 대한 프로토콜 정의는 RFC 2616에 정의되어 있으며,
다음 예제는 HTTP 1.1이 어떤식으로 동작하는지 설명하는 아주 가벼운 예제에 불과하다.
#pragma comment(lib, "ws2_32.lib")
#include <stdio.h>
#include <time.h>
#include <WINSOCK2.H>
#define STD_HTTP_PORT 80
int CreateSvrSock(int nPort)
{
int nSvrSock = 0;
int nRet = 0;
auto int one = 1;
struct sockaddr_in svrAddr;
if ( (nSvrSock = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
{
printf("Socket Create Error : %s\n", strerror(errno));
return -1;
}
if (setsockopt(nSvrSock, SOL_SOCKET, SO_REUSEADDR, (const char *) &one, sizeof(one)) == -1)
{
printf("Error setting SO_REUSEADDR for socket: %s", strerror (errno));
return -1;
}
memset(&svrAddr, 0, sizeof(svrAddr));
svrAddr.sin_family = AF_INET;
svrAddr.sin_addr.s_addr = htonl(INADDR_ANY);
svrAddr.sin_port = htons((u_short)nPort);
if ( (nRet = bind(nSvrSock, (struct sockaddr*)&svrAddr, sizeof(svrAddr))) < 0 )
{
printf("Bind Error : %s\n", strerror(errno));
return -1;
}
if ( listen ( nSvrSock, 5 ) < 0 )
{
printf("Listen Error : %s\n", strerror(errno));
return -1;
}
return nSvrSock;
}
int main(int argc, char **argv)
{
int nSvrSock = 0, nCliSock = 0;
int nRecv = 0, nSend = 0;
int nAddr = sizeof(struct sockaddr_in);
char szBuf[1024];
WSADATA w;
struct sockaddr_in addr;
WSAStartup(MAKEWORD(2, 2), &w);
nSvrSock = CreateSvrSock(STD_HTTP_PORT);
printf("start simple http server 127.0.0.1:%d\n", STD_HTTP_PORT);
while ( (nCliSock = accept(nSvrSock, (struct sockaddr*)&addr, &nAddr)) > 0 )
{
nRecv = recv(nCliSock, szBuf, sizeof(szBuf), 0);
szBuf[nRecv] = 0;
printf("[http client request]\n");
printf("%s\n", szBuf);
printf("=======================================================================\n");
nSend = sprintf(&szBuf[nSend], "HTTP/1.1 200 OK\r\n");
nSend += sprintf(&szBuf[nSend], "Date: Mon, 05 May 2008 03:19:34 GMT\r\n");
nSend += sprintf(&szBuf[nSend], "Server: My mini http server\r\n");
nSend += sprintf(&szBuf[nSend], "Keep-Alive: timeout=15, max=100\r\n");
nSend += sprintf(&szBuf[nSend], "Connection: Keep-Alive\r\n");
nSend += sprintf(&szBuf[nSend], "Content-Type: text/html\r\n");
nSend += sprintf(&szBuf[nSend], "Content-Length: 10\r\n\r\n");
nSend += sprintf(&szBuf[nSend], "%10ld", time(0));
nSend = send(nCliSock, szBuf, nSend, 0);
printf("[http server response]\n");
printf("%s\n", szBuf);
printf("=======================================================================\n");
closesocket(nCliSock);
}
return 0;
}