参考
- 《TCP/IP网络编程》 尹圣雨
Web服务器端
概述
Web服务器端是,基于HTTP(Hypertext Transfer Protocol)协议,将网页对应文件传输给客户端的服务器端。
Hypertext(超文本)是可以根据客户端请求而跳转的结构化信息。
HTTP协议是以超文本传输为目的而设计的应用层协议,同样基于TCP/IP实现。
浏览器属于基于套接字的客户端,因为连接到任意Web服务器端时,浏览器内部也会创建套接字。只是浏览器将服务器端传输的HTML格式的超文本解析为可读性较强的视图。
HTTP协议特点
无状态的Stateless协议
服务器端响应客户端请求后立即断开连接,即服务器端不会维持客户端状态。即使同一客户端再次发送请求,服务器还是以相同的方式处理新请求
为此,Web编程中通常会使用Cookie和Session技术
请求消息的结构
请求消息可以分为请求行、消息头、消息体等
(1)请求行
GET /index.html HTTP/1.1
含义是,请求(GET)index.html文件,希望以1.1版本的HTTP协议进行通信
请求行只能通过1行发送。请求行含有请求方式(目的)信息。典型的请求方式有GET和POST,GET主要用于请求数据,POST主要用于传输数据
(2)消息头
User Agent : Mozilla/5.0
Accept: image/gif, image/jpeg
......
消息头中包含发送请求的浏览器信息、用户认证信息等关于HTTP消息的附加信息 (3)空行 避免边界问题 (4)消息体 消息体仅在以POST方式请求时插入
消息体中装有客户端向服务器端传输的数据
响应消息的结构
响应消息由状态行、头信息、消息体等3个部分构成
(1)状态行
HTTP/1.1 200 OK
含义是,我想用HTTP1.1版本进行响应,你的请求已正确处理(200 OK)
状态行含有关于客户端请求的处理结果。表示“客户端请求的执行结果”的数字称为状态码,例如:
- 200 OK:成功处理了请求
- 404 Not Found:请求的文件不存在
- 400 Bad Request:请求方式错误,请检查
(2)消息头
Server : SimpleWebServer
Content-type : text/html
Content-length : 2048
......
含义是,服务器端名为SimpleWebServer,传输的数据类型为text/html,数据长度不超过2048字节
消息头中含有传输的数据类型和长度等信息
(3)空行 (4)消息体
<html>
......
<body>
......
</html>
通过消息体发送客户端请求的文件数据
实现Web服务器端
Web服务器端采用HTTP协议,即使用IOCP或epoll模型也不会大幅提升性能,因为客户端和服务器端交换1次数据后将立即断开连接,没有足够时间发挥IOCP或epoll的优势。在服务器端和客户端保存较长连接的前提下频繁发送大小不一的消息时(如网游服务器端),才能发挥这2种模型的优势
下面通过多线程模型实现Web服务器端。客户端每次请求时,都创建1个新线程响应 (1)基于Windows
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <WinSock2.h>
#include <process.h>
#include <WS2tcpip.h>
#define BUF_SIZE 2048
#define BUF_SMALL 100
unsigned WINAPI RequestHandler(void* arg);
char* ContentType(char* file);
void SendData(SOCKET sock, char* ct, char* fileName);
void SendErrorMSG(SOCKET sock);
void ErrorHandling(char* message);
int main(int argc, char* argv[])
{
WSADATA wsaData;
SOCKET hServSock, hClntSock;
SOCKADDR_IN servAdr, clntAdr;
HANDLE hThread;
DWORD dwThreadID;
int clntAdrSize;
char tmpbuf[20] = { 0 };
if (argc != 2)
{
printf("Usage : %s <port>\n", argv[0]);
exit(1);
}
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
ErrorHandling("WSAStartup() error!");
}
hServSock = socket(PF_INET, SOCK_STREAM, 0);
memset(&servAdr, 0, sizeof(servAdr));
servAdr.sin_family = AF_INET;
servAdr.sin_addr.s_addr = htonl(INADDR_ANY);
servAdr.sin_port = htons(atoi(argv[1]));
if (bind(hServSock, (SOCKADDR*)&servAdr, sizeof(servAdr)) == SOCKET_ERROR)
{
ErrorHandling("bind() error");
}
if (listen(hServSock, 5) == SOCKET_ERROR)
{
ErrorHandling("listen() error");
}
while (1)
{
clntAdrSize = sizeof(clntAdr);
hClntSock = accept(hServSock, (SOCKADDR*)&clntAdr, &clntAdrSize);
printf("Connection Request : %s:%d\n", inet_ntop(AF_INET, &clntAdr.sin_addr, tmpbuf, sizeof(tmpbuf)), ntohs(clntAdr.sin_port));
hThread = (HANDLE)_beginthreadex(NULL, 0, RequestHandler, (void*)hClntSock, 0, (unsigned*)&dwThreadID);
}
closesocket(hServSock);
WSACleanup();
return 0;
}
unsigned WINAPI RequestHandler(void* arg)
{
printf("RequestHandler\n");
SOCKET hClntSock = (SOCKET)arg;
char buf[BUF_SIZE];
char method[BUF_SMALL];
char ct[BUF_SMALL];
char fileName[BUF_SMALL];
char* tmp = NULL;
recv(hClntSock, buf, BUF_SIZE, 0);
if (strstr(buf, "HTTP/") == NULL)
{
SendErrorMSG(hClntSock);
closesocket(hClntSock);
return 1;
}
strcpy_s(method, BUF_SMALL, strtok_s(buf, " /", &tmp));
if (strcmp(method, "GET"))
{
SendErrorMSG(hClntSock);
}
strcpy_s(fileName, BUF_SMALL, strtok_s(NULL, " /", &tmp));
strcpy_s(ct, BUF_SMALL, ContentType(fileName));
SendData(hClntSock, ct, fileName);
return 0;
}
void SendData(SOCKET sock, char* ct, char* fileName)
{
printf("SendData\n");
printf("filename:%s\n", fileName);
char protocol[] = "HTTP/1.0 200 OK\r\n";
char servName[] = "Server:simple web server\r\n";
char cntLen[] = "Content-length:2048\r\n";
char cntType[BUF_SMALL];
char buf[BUF_SIZE];
FILE* sendFile;
sprintf_s(cntType, BUF_SMALL, "Content-type:%s\r\n\r\n", ct);
if ((fopen_s(&sendFile, fileName, "r")) != 0)
{
SendErrorMSG(sock);
return;
}
send(sock, protocol, strlen(protocol), 0);
send(sock, servName, strlen(servName), 0);
send(sock, cntLen, strlen(cntLen), 0);
send(sock, cntType, strlen(cntType), 0);
while (fgets(buf, BUF_SIZE, sendFile) != NULL)
{
send(sock, buf, strlen(buf), 0);
}
closesocket(sock);
}
void SendErrorMSG(SOCKET sock)
{
char protocol[] = "HTTP/1.0 400 Bad Request\r\n";
char servName[] = "Server:simple web server\r\n";
char cntLen[] = "Content-length:2048\r\n";
char cntType[] = "Content-type:text/html\r\n\r\n";
char content[] = "<html><head><title>NETWORK</title></head>"
"<body><font size=+5><br> 发生错误!查看请求文件名和请求方式!"
"</font></body></html>";
send(sock, protocol, strlen(protocol), 0);
send(sock, servName, strlen(servName), 0);
send(sock, cntLen, strlen(cntLen), 0);
send(sock, cntType, strlen(cntType), 0);
send(sock, content, strlen(content), 0);
closesocket(sock);
}
char* ContentType(char* file)
{
char extension[BUF_SMALL];
char fileName[BUF_SMALL];
char* tmp;
strcpy_s(fileName, BUF_SMALL, file);
strtok_s(fileName, ".", &tmp);
strcpy_s(extension, BUF_SMALL, strtok_s(NULL, ".", &tmp));
if (!strcmp(extension, "html") || !strcmp(extension, "htm"))
{
return "text/html";
}
else
{
return "text/plain";
}
}
void ErrorHandling(char* message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
(2)基于Linux
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <pthread.h>
#define BUF_SIZE 1024
#define SMALL_BUF 100
void* request_handler(void* arg);
void send_data(FILE* fp, char* ct, char* file_name);
char* content_type(char* file);
void send_error(FILE* fp);
void error_handling(char* message);
int main(int argc, char* argv[])
{
int serv_sock, clnt_sock;
struct sockaddr_in serv_adr, clnt_adr;
int clnt_adr_size;
char buf[BUF_SIZE];
pthread_t t_id;
if (argc != 2)
{
printf("Usage : %s <port>\n", argv[0]);
exit(1);
}
serv_sock = socket(PF_INET, SOCK_STREAM, 0);
memset(&serv_adr, 0, sizeof(serv_adr));
serv_adr.sin_family = AF_INET;
serv_adr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_adr.sin_port = htons(atoi(argv[1]));
if (bind(serv_sock, (struct sockaddr*)&serv_adr, sizeof(serv_adr)) == -1)
{
error_handling("bind() error");
}
if (listen(serv_sock, 20) == -1)
{
error_handling("listen() error");
}
while (1)
{
clnt_adr_size = sizeof(clnt_adr);
clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_adr, &clnt_adr_size);
printf("Connection Request : %s:%d\n", inet_ntoa(clnt_adr.sin_addr), ntohs(clnt_adr.sin_port));
pthread_create(&t_id, NULL, request_handler, &clnt_sock);
pthread_detach(t_id);
}
close(serv_sock);
return 0;
}
void* request_handler(void* arg)
{
int clnt_sock = *((int*)arg);
char req_line[SMALL_BUF];
FILE* clnt_read;
FILE* clnt_write;
char method[10];
char ct[15];
char file_name[30];
clnt_read = fdopen(clnt_sock, "r");
clnt_write = fdopen(dup(clnt_sock), "w");
fgets(req_line, SMALL_BUF, clnt_read);
if (strstr(req_line, "HTTP/") == NULL)
{
send_error(clnt_write);
fclose(clnt_read);
fclose(clnt_write);
return;
}
strcpy(method, strtok(req_line, " /"));
strcpy(file_name, strtok(NULL, " /"));
strcpy(ct, content_type(file_name));
if (strcmp(method, "GET") != 0)
{
send_error(clnt_write);
fclose(clnt_read);
fclose(clnt_write);
return;
}
fclose(clnt_read);
send_data(clnt_write, ct, file_name);
}
void send_data(FILE* fp, char* ct, char* file_name)
{
char protocol[] = "HTTP/1.0 200 OK\r\n";
char server[] = "Server:Linux Web Server \r\n";
char cnt_len[] = "Content-length:2048\r\n";
char cnt_type[SMALL_BUF];
char buf[BUF_SIZE];
FILE* send_file;
sprintf(cnt_type, "Content-type:%s\r\n\r\n", ct);
send_file = fopen(file_name, "r");
if (send_file == NULL)
{
send_error(fp);
return;
}
fputs(protocol, fp);
fputs(server, fp);
fputs(cnt_len, fp);
fputs(cnt_type, fp);
while (fgets(buf, BUF_SIZE, send_file) != NULL)
{
fputs(buf, fp);
fflush(fp);
}
fflush(fp);
fclose(fp);
}
char* content_type(char* file)
{
char extension[SMALL_BUF];
char file_name[SMALL_BUF];
strcpy(file_name, file);
strtok(file_name, ".");
strcpy(extension, strtok(NULL, "."));
if (!strcmp(extension, "html") || !strcmp(extension, "htm"))
{
return "text/html";
}
else
{
return "text/plain";
}
}
void send_error(FILE* fp)
{
char protocol[] = "HTTP/1.0 400 Bad Request\r\n";
char server[] = "Server:Linux Web Server \r\n";
char cnt_len[] = "Content-length:2048\r\n";
char cnt_type[] = "Content-type:text/html\r\n\r\n";
char content[] = "<html><head><title>NETWORK</title></head>"
"<body><font size=+5><br>发生错误!查看请求文件名和请求方式"
"</font></body></html>";
fputs(protocol, fp);
fputs(server, fp);
fputs(cnt_len, fp);
fputs(cnt_type, fp);
fflush(fp);
}
void error_handling(char* message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
|