前言
先说说弄了个什么,访问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;
}