编写web服务器来理解HTTP协议

前言

先说说弄了个什么,访问web服务的80端口,简单的web服务器解析http协议后,发送当前目录的index.html给浏览器,输入xxx,服务器回应hello word:xxx。
在这里插入图片描述

GET 请求

敲击127.0.0.1 会默认访问本机的80端口。服务器得到的数据如下
第一行 GET / HTTP/1.1 表示get请求,使用1.1版本,中间的 / 为get所带的参数,比如 GET /index.html?firstname=%E5%91%A8%E5%A4%A7%E5%94%90 HTTP/1.1
第二行空格
后面就是请求头,如host(主机地址),connection (连接的类型为保活长连接),accept(接收的数据类型) 接收的编码格式
最后是请求数据 get请求是没有这部分的。post请求就会将数据放在这里
在这里插入图片描述

GET 回应

第一行:状态行 HTTP/1.0 200 OK
接着是状态报头
接着是 空行
最后发送 回应数据

HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8

<html>
      <head></head>
      <body>
      </body>
</html>

index.html资源文件

index.html 放在服务器的当前目录

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>c语言web服务器测试网页</title>
</head>
<body>

<h1><center> c语言web服务器测试网页</center></h1>
<center> 支持get请求</center>
<center><form action="index.html" method="GET">
访客姓名:<br>
<input type="text" name="firstname" >
<br>

<input type="submit" value="访问">
</form> </center>
</body>
</html>

代码

逻辑简单说就是,编写socket server ,开启线程不断监听连接,有连接就调用accept_request()处理,获取请求的第一行,判断是否是get,提取get的参数。失败回应unimplemented(),成功回应消息头,和index.html资源。

int accept_request(int); ----------------------->处理主体
int get_line(int, char *, int);-------------------->获取第一行数据
void headers(int);------------------------------->回应头
int startup(u_short *);-------------------------->开启web服务
void unimplemented(int);----------------------> 回应错误
int data_real(char *data, char *data2);---->判断get请求是否有参数
int data_trans(char *data, char * data2)---->判断是否有中文字符,有则转换
(url传输中,将中文字符转换为%xx%xx%xx,utf 8一个中文3个字符,所以一个中文对应3个%,xx为该字符的16进制形式)

#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS

#include<iostream>
#include <winsock2.h>
#include<string.h>
#include<thread>

#pragma comment (lib, "ws2_32.lib")  //加载 ws2_32.dll
#define ISspace(x) isspace((int)(x))

int accept_request(int);
int get_line(int, char *, int);
void headers(int);
int startup(u_short *);
void unimplemented(int);
int  data_real(char *data, char *data2);
int data_trans(char *data, char * data2)

int get_line(int sock, char *buf, int size)
{
	int i = 0;
	char c = '\0';
	int n;

	while ((i < size - 1) && (c != '\n'))
	{
		n = recv(sock, &c, 1, 0);//接受一个字符存入c 
								 /* DEBUG printf("%02X\n", c); */
		if (n > 0)//接收成功 
		{
			if (c == '\r')//回车 
			{
				n = recv(sock, &c, 1, MSG_PEEK);//MSG查看当前数据。数据将被复制到缓冲区中,但并不从输入队列中删除
												/* DEBUG printf("%02X\n", c); */
				if ((n > 0) && (c == '\n'))//如果获得数据且不是换行 
					recv(sock, &c, 1, 0);
				else
					c = '\n';
			}
			buf[i] = c;
			i++;
		}
		else
			c = '\n';
	}
	buf[i] = '\0';

	return(i);
}

int startup()
{
	int httpd = 0;//socket_server
	struct sockaddr_in name;
	httpd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);//协议族(ipv4),协议类型(tcp),协议编号 
	if (httpd == -1)
		printf("socket");
	memset(&name, 0, sizeof(name));//将name中的sizeof个字节替换为0 
	name.sin_family = AF_INET;
	name.sin_port = htons(80);
	name.sin_addr.s_addr = htonl(INADDR_ANY);//0.0.0.0任意地址 
	if (bind(httpd, (struct sockaddr *)&name, sizeof(name))< 0)
		printf("bind");
	if (listen(httpd, 5) < 0)//监听httpd,最多长度5 
		printf("listen");
	return(httpd);
}
void unimplemented(int client)
{
	char buf[1024];

	sprintf(buf, "HTTP/1.0 501 Method Not Implemented\r\n");
	send(client, buf, strlen(buf), 0);
	sprintf(buf, "Server: jdbhttpd/0.1.0\r\n");//
	send(client, buf, strlen(buf), 0);
	sprintf(buf, "Content-Type: text/html\r\n");
	send(client, buf, strlen(buf), 0);
	sprintf(buf, "\r\n");
	send(client, buf, strlen(buf), 0);
	sprintf(buf, "<HTML><HEAD><TITLE>Method Not Implemented\r\n");
	send(client, buf, strlen(buf), 0);
	sprintf(buf, "</TITLE></HEAD>\r\n");
	send(client, buf, strlen(buf), 0);
	sprintf(buf, "<BODY><P>HTTP request method not supported.\r\n");
	send(client, buf, strlen(buf), 0);
	sprintf(buf, "</BODY></HTML>\r\n");
	send(client, buf, strlen(buf), 0);
}


int  data_real(char *data, char *data2)
{
	char *pbuf1 = data;
	char *pbuf2 = data;
	if (strstr(data, "firstname") != NULL)
	{
		
		while (*++pbuf1 != '=');
		while (*++pbuf2  != '\0');
		if (++pbuf1 == pbuf2)
			return -1;
		while (pbuf1 != pbuf2)
		{
			*data2++ = *pbuf1++;
		};
		*data2 = '\0';
	}
	return 0;
}


int data_trans(char *data, char * data2)
{
	if (strstr(data, "%") != NULL)
	{
		char *pbuf = data;
		char buf[100];
		int t = 0;
		while (*pbuf != '\0')
		{

			if (*pbuf == '%')
			{
				char date=0;
				if (*++pbuf >= '0'&& *pbuf <= '9')
				{
					date |= *pbuf - '0';
				}
				else if (*pbuf >= 'a'&& *pbuf <= 'f')
				{
					date |= *pbuf - 'a'+10;
				}
				else
				{
					date |= *pbuf - 'A' + 10;
				}
				//第二个字符
				date <<= 4;
				if (*++pbuf >= '0'&& *pbuf <= '9')
				{
					date |= *pbuf - '0';
				}
				else if (*pbuf >= 'a'&& *pbuf <= 'f')
				{
					date |= *pbuf - 'a' + 10;
				}
				else
				{
					date |= *pbuf - 'A' + 10;
				}
				buf[t++] = date;
			}
			else
			{
				buf[t++] = *pbuf;
			}
			pbuf++;
		}
		buf[t] = '\0';
		memcpy(data2,buf,100);
		return 0;
	}
	return -1;
}
int accept_request(int client)
{
	FILE *fp;
	char buf[1024];
	char buf2[100];
	char buf3[1024];
	char buf4[100];
	char *pbuf = buf;
	int numchars;
	char *query_string = NULL;

	numchars = get_line(client, buf, sizeof(buf));//自定义函数 
	printf("%s\n",buf);
	recv(client, (char *)buf3, 1024, 0);
	printf("%s\n", buf3);
	if (strstr(buf, "GET") !=NULL || strstr(buf,"get")!=NULL)
	{

		char  str[1000];
		fp = fopen("./index.html", "r");
		if (!fp)
		{
			unimplemented(client);
		}
		headers(client);
		while (!feof(fp))
			      {
			          fgets(str, 1024, fp);  //读取一行
					  send(client, str, strlen(str), 0);
			      }
		      fclose(fp);                     //关闭文件

			  time_t t;
			  struct tm * lt;
			  char date[40];
			  time(&t);//获取Unix时间戳。
			  lt = localtime(&t);//转为时间结构。
			  sprintf(date, "<center>%d-%d-%d %d:%d</center>", lt->tm_year + 1900, lt->tm_mon+1, lt->tm_mday, lt->tm_hour, lt->tm_min);
			  send(client, date, strlen(date), 0);
			  if (strstr(buf, "?")!=NULL)
			  {
				 
				  pbuf = buf;
				  	
				  int t=0;
				  while (*pbuf++ != '?' );
				  printf("---%s\n", pbuf);
				  while (*pbuf != '\r' &&*pbuf != ' ' &&*pbuf != '\0')
				  {
					  buf2[t++] = *pbuf++;
				  }
				  buf2[t] = '\0';

				  if (data_real(buf2, buf4)==0)
				  {
					  data_trans(buf4, buf4);
					  strcpy(str, "<center>hello word:");
					  send(client, str, strlen(str), 0);
					  send(client, buf4, strlen(buf4), 0);
					  send(client,"</center>",9,0);
				  }
			  }	  
	}
	else if (strstr(buf, "POST") != NULL || strstr(buf, "post")!= NULL)
	{

	}
	else
	{
		unimplemented(client);
		return 0;
	}
	closesocket(client);
	return 0;
}


void headers(int client)
{
	char buf[1024];
	strcpy(buf, "HTTP/1.0 200 OK\r\n");
	send(client, buf, strlen(buf), 0);
	strcpy(buf, "Server: httpd/0.1.0\r\n");
	send(client, buf, strlen(buf), 0);
	sprintf(buf, "Content-Type: text/html\r\n");
	send(client, buf, strlen(buf), 0);
	strcpy(buf, "\r\n");
	send(client, buf, strlen(buf), 0);
}
int main() {
	SOCKET servSock;//服务器套接字
	struct sockaddr_in sockAddr;
	SOCKADDR clntAddr;
	SOCKET client_sock;
	int nSize=sizeof(SOCKADDR);;
	int n = 1;
	//pthread_t newthread;
	//初始化 DLL
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2, 2), &wsaData);//套接字库函数
	servSock = startup();
	//printf("			 ==mini c语言版 web服务器==\n");
	while (1)
	{
		client_sock = accept(servSock, (SOCKADDR*)&clntAddr, &nSize);
		//等待客户请求的到来,当请求到来后接收连接请求,返回一个新的对应于此连接的套接字
		// 客户机    数据   发送长度
		if (client_sock != -1)
			printf("获得连接\n");
		
		std::thread(accept_request, client_sock).detach();
		
	}

	//closesocket(servSock);
	WSACleanup();
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

工农村贴膜小哥

我倒是要看看是那个憨憨在给我打

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值