There are now a lot of powerful HTTP servers, Apache, IIS, we should be familiar with
In fact, many HTTP servers have the most basic workflow:
1. Initialize the working environment, listen to external requests in fixed port (80)
2. Receive request
3. Establish a connection
4. Send a response header
5. Send a response
6. Interrupt connection
Here is the simplest HTTP server example, with Winsock implementation
Why is the easiest thing because it receives the request, the response header and response content sent are directly specified.
Can't distinguish between different GET, POST, and HEAD requests.
#include "winsock.h" #include "stdlib.h" #include "stdio.h" #include "string.h" #pragma Comment (lib, "wsock32") /// required library files required
Void main () {/ initialization Winsock environment WSADATA WSADATA; Word WVersion = MakeWord (2,0); / Winsock 2.0 IF (WSAStartup (WSADATA)! = 0) {Printf ("INITALIZE FAILED! / N"); wsacleanup (); Exit (1);
Int Sock, Csock, Length; // Sock is the server-side listening socket, CSOCK is a client connection socket length = sizeof (struct sockaddr);
struct sockaddr_in server_ipaddr, client_ipaddr; // the client and server for obtaining address information memset (& server_ipaddr, 0, length); server_ipaddr.sin_family = AF_INET; server_ipaddr.sin_port = htons (80); server_ipaddr.sin_addr.s_addr = inet_addr ( " 211.81.55.200 ");
CHAR BUFF [4096]; INT NBUFF;
SOCK = Socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); // Bind IF (Bind (STRUCKADDR *) & Server_IpAddr, Length) == Socket_ERROR) {Printf ("Bind Error / N"); wsacleanup (); EXIT (1);} Listening IF (Listen (Sock, 5) == Socket_ERROR) {Printf ("Listen Error / N"); wsacleanup (); exit (1);}
/ CHAR Headers [1000]; // Save Head / Head Format CHAR HDRFMT [] = "HTTP / 1.0 200 OK / R / N" "Server: MySocket Server / R / N" Date:% S / R / n "" Content-Type: TEXT / HTML / R / N "" Accept-ranges: BYTES / R / N "" Content-length:% D / R / N / R / N "; char * strgmtnow =" 08 / 15/14 22:53:00 gmt "; /// will specify a time wsprintf (headers, hdrfmt, (const char *) strgmtnow, strlen (customhtml)); // To transfer web content char Customhtml [] = " / r / n" "
/ R / N"Welcome to my home page p> / r / n" "
end p> / r / n "
p> / r / n" body> html> / R / n / r / n "; // while (1) {// So after the connection, generate new socket /// used to pass messages with the client CSock = Accept (Sock, (Steruct SockAddr * ) & client_ipaddr, & length); if (csock == socket_error) {Printf ("Listen Error / N"); wsacleanup (); EXIT (1);} nbuff = Recv (CSOCK, BUFF, 4095, 0); BUFF [NBuff, ] = '/ 0'; Printf ("% s", buff); / Sending the header Send (Csock, Headers, Strlen (Headers), 0); / Send Content Send (Csock, CustomHTML, Strlen (Customhtml), 0); / Close this connection closesocket Csock);
}
}