应用层:
协议:
网络计算机服务端:
#include "封装多线程TCP服务端.hpp"
#include <sstream>
int main() {
TcpThraedServer server;
server.Start("0.0.0.0", 9090, [](const std::string& req, std::string* resp){
//1.反序列化
std::stringstream ss(req);
int num1 = 0;
int num2 = 0;
std::string op;
ss >> num1;
ss >> num2;
ss >> op;
printf("req=%d,%d,%s\n", num1, num2, op.c_str());
//2.进行计算
int ret = 0;
if (op =="+") {
ret = num1 + num2;
}else if (op == "-") {
ret = num1 - num2;
}
//3.结果再序列化
//*resp = std::to_string(ret);
std::stringstream ss_resp;
ss_resp << ret;
*resp == ss_resp.str();
});
return 0;
}
网络计算器客户端:
#include "封装的TCP客户端.hpp"
#include <sstream>
int main() {
TcpClient client;
bool ret = client.Connect("127.0.0.1", 9090);
if (!ret) {
return 1;
}
while (true) {
printf("请输入两个操作数:\n");
fflush(stdout);
int num1 = 0;
int num2 = 0;
char op[10] = { 0 };
scanf("%d %d %s", &num1, &num2, op);
//序列化
std::stringstream ss;
ss << num1 << " " << num2 << " " << op;
//给服务器发送数据
client.Send(ss.str());
std::string resp;
client.Recv(&resp);
printf("resp:%s\n", resp.c_str());
}
return 0;
}
序列化有一个 JSON 方式序列化 。
HTTP:
网站上运用。
认识URL:平时说的网址,链接。
fiddler 抓包工具:
HTTP协议的格式:
HTTP的方法:
HTTP的状态码:
2* 请求成功
3* 重定向
4* 客户端出错错误
5* 服务器出现错误
HTTP常见的Header:
- Content-Type:数据类型(text/html等) ,描述body
- Content-Length:Body的长度
- Host:客户端告知服务器,所请求的资源是在哪个主机的哪个端口上;
- User-Agent:声明用户的操作系统和浏览器版本信息;
- referer:当前页面是从哪个页面跳转过来的;
- location:搭配3xx状态码使用,告诉客户端接下来要去哪里访问;
- Cookie:用于在客户端存储少量信息。一个保存在浏览器端的字符串。字符串的含义是程序员决定的,外部用户不知道什么含义。最最常见的内容是用户的身份信息。就是第一次登陆淘宝之后,再次点开淘宝的各种界面就不用登陆了。当我们登陆账号之后,服务器回返回一个身份信息字符串,浏览器保存在cookie中,是身份标识(session id)这是其中的一种。
最简单的HTTP服务器
//HTTP协议基于 TCP //HTTP 3.0 可以基于 UDP #include "封装多线程TCP服务端.hpp" void HttpProcess(const std::string& req, std::string* resp) { (void)req; std::string first_line = "HTTP/1.1 200 ok\n"; std::string body = "<heml><div>hello world</div></html>"; std::string header = "Content_Type:text/html\nContent_Length:" + std::to_sting(body.size()) + "\n"; *resp = first_line + header + "\n" + body; } int main() { TcpThraedServer server; server.Start("0.0.0.0", 9090, HttpProcess); return 0; }
注:在虚拟机搭建服务器,必须先关闭防火墙
- root
- service firewalld stop(关闭防火墙的命令) #centos 7
- service iptables stop(关闭防火墙的命令) #centos 6
- service firewalld status(查看是否关机,其状态)
- service firewalld start(打开防火墙)