文章目录
1.HTTP的应用演示
1.1知识预知
1.2代码
#include <iostream>
using namespace std;
#include <string>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
class Server
{
private:
int port;
int lsock;
public:
Server(int _port)
:port(_port)
,lsock(-1)
{}
void InitServer()
{
signal(SIGCHLD,SIG_IGN);
lsock=socket(AF_INET,SOCK_STREAM,0);
if(lsock < 0)
{
cerr<<"sock error"<<endl;
exit(2);
}
struct sockaddr_in local;
local.sin_family=AF_INET;
local.sin_port=htons(port);
local.sin_addr.s_addr=INADDR_ANY;
if(bind(lsock,(struct sockaddr*)&local,sizeof(local)) < 0)
{
cerr<<"bind error"<<endl;
exit(3);
}
if(listen(lsock,5) < 0)
{
cerr<<"listen error"<<endl;
}
}
void EchoHttp(int sock)
{
char request[1024];
size_t s=recv(sock,request,sizeof(request)-1,0);//假设可以读完报文(字节流)
if(s>0)
{
request[s]=0;
cout<<request<<endl;//http全是文本,不做处理直接输出
string response="HTTP/1.0 303 FOUND \r\n";//响应首行
response+= "Content-type: text/html\r\n"; //Content-Type:数据类型(text/html等),响应一个html页面
response+= "location: https://www.baidu.com";
//短链接,游览器根据close信息知晓已经响应完毕,因此客户不写content length
response+="\r\n";
//response+="\
// <!DOCTYPE html>\
// <html>\
// <head>\
// <title>我的http</title>\
// </head>\
// <body>\
// <h1>HI!WELCOME</h1>\
// <p>hello word!</p>\
// </body>\
// </html>";
send(sock,response.c_str(),response.size(),0);
}
close(sock);//短链接
}
void start()
{
while(true)
{
sockaddr_in peer;
socklen_t len=sizeof(peer);
int sock=accept(lsock,(struct sockaddr*)&peer,&len);
if(sock < 0)
{
cerr<<"accept error"<<endl;
continue ;
}
cout<<"get a new link"<<endl;
if(fork()==0)
{
close(lsock);
EchoHttp(sock);
exit(0);//短链接
}
close(sock);
}
}
~Server()
{
if(lsock!=-1)
close(lsock);
}
};
#include "HttpServer.hpp"
void Usage(string str)
{
cout<<"Usage:"<<str<<endl;
cout<<"please enter port"<<endl;
}
int main(int argc,char *argv[])
{
if(argc!=2)//程序和端口
{
Usage(argv[0]);
exit(1);
}
Server *se=new Server(atoi(argv[1]));
se->InitServer();
se->start();
delete se;
return 0;
}
1.3实验效果
1.4协议只是给游览器的一种参考
1.5网页重定向
网页重定向分为临时重定向和永久重定向:
301的含义是“永久”:
如果域名、服务器、网站架构发生了大幅度的改变,比如启用了新域名、服务器切换到了新机房、网站目录层次重构,这些都算是“永久性”的改变,原来的URI已经不能用了,必须用301“永久重定向”,通知浏览器和搜索引擎更新到新地址。
302的含义是“临时”:
原来的URI在将来的某个时间点还会恢复正常,常见的应用场景就是系统维护,把网站重定向到一个通知页面,告诉用户过一会儿再来访问。另一种用法就是“服务降级”,比如双十一促销的时候,把订单查询、领积分等不重要的功能入口暂时关闭,保证核心服务能够正常运行。
2.HTTP和HTTPS
2.1HTTP的缺陷
HTTP的速度相对于HTTPS来说,是更快一些的,但是HTTP传输的内容是没有经过加密的,因此用户层的一些隐式数据很容易就被暴露,主要有以下几种不足:
1.通信使用明文(不加密),可能被窃取
2.不验证通信方的身份,因此可能遭遇伪装
3.无法验证报文的完整性,所以有可能遭到篡改
2.2HTTPS
2.2.1https是什么
https本质上也是http,只是,https对用户层的数据进行了加密,使得应用层用户的数据更加的安全
2.2.2对称加密
客户端有一个密钥、服务器也有一个密钥。用密钥对数据进行加密和解密,就叫做对称加密