计算机网络中的OSI七层模型
计算机网络中的OSI(Open Systems Interconnection)七层模型
Is a theoretical framework for describing the process of data communication in computer networks. The OSI model 计算机网络通信
divides the process into seven levels, and each level has its specific functions and protocols. This layered structure is helpful for research and understanding in computer network 通信原理
. The following are the various layers of the OSI seven-layer model and their main functions:
应用层
It is the seventh layer of the OSI model and is also the interface between 网络应用程序
and . 网络协议
The application layer is mainly responsible for providing users with various application services, such as file transfer, email, and Web browsing.
表示层
It is the sixth layer of the OSI model, which is mainly responsible for processing the representation of data transmitted in the network, such as data 加密、解密、压缩、解压缩
. The presentation layer ensures communication between different systems 数据兼容性
.
会话层
It is the fifth layer of the OSI model and is mainly responsible for establishing, maintaining and terminating communication sessions between applications. The session layer provides synchronization and confirmation mechanisms for data exchange.
传输层
It is the fourth layer of the OSI model, which is mainly responsible for providing reliable, end-to-end data transmission services between the source host and the target host. The transport layer achieves reliable data transmission by segmenting, encapsulating, and reassembling data. Common transport layer protocols include TCP(传输控制协议)
and UDP(用户数据报协议)
.
网络层
It is the third layer of the OSI model, which is mainly responsible for 数据包从源主机路
sending hosts to the target host. The network layer is mainly responsible 逻辑寻址、路由选择和分组转发
. Common network layer protocols include IP(互联网协议)
and ICMP(互联网控制报文协议)
.
数据链路层
It is the second layer of the OSI model. It is mainly responsible for encapsulating data packets from the network layer into frames and transmitting them in the same LAN. The data link layer is mainly responsible for physical addressing, data framing, error detection and flow control. Common data link layer protocols include 以太网(Ethernet)、令牌环(Token Ring)和无线局域网(Wi-Fi)
etc.
物理层
It is the first layer of the OSI model and is mainly responsible for transparent transmission of bit streams on physical media. The physical layer mainly focuses on issues such as hardware interfaces, electrical characteristics, optical fibers, and wireless transmission.
The OSI seven-layer model provides a general framework to help study and understand communication principles in computer networks. In practical applications, we usually use TCP/IP四层模型
, it includes 应用层、传输层、网络层和链路层
, and has a certain correspondence with the OSI model.
The necessity of an HTML framework
HTML框架
The main reason for layered design is to improve code readability, maintainability, and reusability. Layering HTML框架
can improve the structure and logic of the overall project, making it easier for developers to better understand and modify the code. A layered design has the following advantages:
- Improve readability: By dividing the HTML frame into different layers, the code structure can be made clearer, which helps developers quickly understand the function of the code.
- Ease of maintenance: The layered design helps to modularize functions, so that a module can be easily modified or replaced without affecting other parts of the code. This helps improve the maintainability of the project.
- Reusability: Layering the HTML framework can extract common parts into reusable components, so that these components can be reused in different projects and improve development efficiency.
- Adaptability: Layered design can make the HTML framework easier to adapt to different devices and screen sizes, improving project compatibility.
- Ease of collaboration: In large projects, there are often multiple developers involved. Through layered design, developers can focus on their own modules, reducing code conflicts and communication costs.
HTML框架的组成
The HTML framework includes Application层``middleware层``route层``codec层``transport层
Application层
The application layer usually includes code related to business logic, such as the controller (Controller), view (View) and model (Model) of a web application. The main role of the application layer is to process user requests and return corresponding responses.
Middleware层
The middleware layer is a layer between the application layer and the underlying framework, responsible for handling some common functions, such as authentication, authorization, caching, logging, etc. The middleware layer helps to separate business logic from common functions, making the application layer more concise and easier to maintain.
Route层
The routing layer is responsible for processing URLs and HTTP methods (such as GET, POST, etc.) of HTTP requests, and dispatching requests to corresponding controllers and methods. The main function of the routing layer is to locate specific function codes according to the URL mapping.
Codec层
The codec layer is responsible for encoding and decoding data. In web development, encoding and decoding usually involve the processing of front-end technologies such as HTML, CSS, and JavaScript, as well as the processing of data exchange formats such as JSON and XML. The main function of the codec layer is to convert data into a specific format for transmission and processing between different layers.
Transport层
The transport layer is responsible for handling the underlying network communication, such as the use of protocols such as TCP and UDP. In web development, the transport layer usually involves the processing of the HTTP protocol, including the creation, sending, and receiving of requests and responses. The main role of the transport layer is to ensure the reliable transmission of data and the correct routing in the network.
These layers may vary in different frameworks and scenarios in real applications. However, judging from the description you provided, they are respectively responsible for handling different functions in the web application, and together constitute a complete web development framework.
HTML框架和服务端客户端之间的通信对比
Application层
application layer design
The application layer design is mainly to set various types 接口
for 路由
use.
For example in the big project in the advanced version of the byte backend 注册接口
.
/douyin/user/register/ - user registration interface
When a new user registers, just provide a user name, password, and nickname, and the user name needs to be unique. Returns the user id and permission token after the creation is successful.
Interface Type
POST
Interface definition
go
复制代码
syntax = "proto2";
package douyin.core;
message douyin_user_register_request {
required string username = 1; // 注册用户名,最长32个字符
required string password = 2; // 密码,最长32个字符
}
message douyin_user_register_response {
required int32 status_code = 1; // 状态码,0-成功,其他值-失败
optional string status_msg = 2; // 返回状态描述
required int64 user_id = 3; // 用户id
required string token = 4; // 用户鉴权token
}
go
复制代码
func Register(username, password string) (id int64, token int64, err error) {
if len(username) > 32 {
return 0, 0, errors.New("用户名过长,不可超过32位")
}
if len(password) > 32 {
return 0, 0, errors.New("密码过长,不可超过32位")
}
// 先查布隆过滤器,不存在直接返回错误,降低数据库的压力
if userNameFilter.TestString(username) {
return 0, 0, errors.New("用户名已经存在!")
}
//雪花算法生成token
node, err := snowflake.NewNode(1) //这里的userIdInt64就是 User.Id(主键)
if err != nil {
log.Println("雪花算法生成id错误!")
log.Println(err)
}
token1 := node.Generate().Int64()
tokenStr := strconv.FormatInt(token1, 10)
user := domain.User{}
// 再查缓存
data, err := dao.RedisClient.Get(context.Background(), tokenStr).Result()
if err == redis.Nil {
fmt.Println("token does not exist")
} else if err != nil {
fmt.Println("Error:", err)
} else {
num, err := strconv.ParseInt(data, 10, 64)
if err != nil {
fmt.Println("Error:", err)
return num, 0, err
}
return num, token1, nil
}
//在查数据库
user = domain.User{}
dao.DB.Model(&domain.User{}).Where("name = ?", username).Find(&user)
if user.Id != 0 {
return 0, 0, errors.New("用户已存在")
}
user.Name = username
// 加密存储用户密码
user.Salt = randSalt()
buf := bytes.Buffer{}
buf.WriteString(username)
buf.WriteString(password)
buf.WriteString(user.Salt)
pwd, err1 := bcrypt.GenerateFromPassword(buf.Bytes(), bcrypt.MinCost)
if err1 != nil {
return 0, 0, err
}
user.Pwd = string(pwd)
//存在mysql里边
dao.DB.Model(&domain.User{}).Create(&user)
//再把用户id作为键 用户的所有信息作为值存在其中
//用户信息的缓存是 保存在redis中 一个以id为键 user json为值
jsonuser, err1 := MarshalUser(user)
if err1 != nil {
fmt.Println("err1", err1)
return 0, 0, err1
}
err = dao.RedisClient.Set(context.Background(), strconv.FormatInt(user.Id, 10), jsonuser, 0).Err()
if err != nil {
fmt.Println("err", err)
return 0, 0, err
}
// 布隆过滤器中加入新用户
userIdFilter.AddString(strconv.FormatInt(user.Id, 10))
userNameFilter.AddString(username)
return user.Id, token1, nil
}
The registration function of this interface is implemented: store all the information in mysql, of course redis also has this information, and of course the username also exists in the Bouillon filter, when we receive the user's username, we will first check whether it is in the Bouillon filter If it exists, it will directly return err, if it does not exist, then query it in redis, because redis is lighter than mysql, so we need to check it in redis first, and if it can’t be found, then check it in mysql , I can’t find it, indicating that I haven’t registered, you can register.
命名规范
Follow the principles of naming conventions.
Middleware层中间件
The middleware in the gin framework is divided into global middleware and local middleware. So what is middleware? Middleware is software that provides common services and functionality to applications. Data management, application serving, messaging, authentication, and API management often go through middleware. In the gin framework, all our API interfaces must pass through our middleware, and we can do some interception processing in the middleware.
Common Models of Middleware
global middleware
This is registered when the service starts, and global means that all API interfaces will pass through here. Gin's middleware is Use
set through a method, which receives a variable parameter, so we can set multiple middleware at the same time.
First define as follows
go
复制代码
// 1.创建路由
r := gin.Default() //默认带Logger(), Recovery()这两个内置中间件
r:= gin.New() //不带任何中间件
// 注册中间件
r.Use(MiddleWare())
r.Use(MiddleWare2())
Please be aware of
gin.Default()
Logger
By default, and middleware are used Recovery
, among which: Logger middleware writes logs gin.DefaultWriter
even if GIN_MODE=release is configured. Recovery middleware will do recover
anything panic
. If there is a panic, a 500 response code will be written. If you don't want to use the above two default middleware, you can create gin.New()
a new route without any default middleware.
go
复制代码
// 定义中间
func MiddleWare() gin.HandlerFunc {
return func(c *gin.Context) {
t := time.Now()
fmt.Println("中间件开始执行了")
// 设置变量到Context的key中,可以通过Get()取
c.Set("request", "这是中间件设置的值")
status := c.Writer.Status()
fmt.Println("中间件执行完毕", status)
t2 := time.Since(t)
fmt.Println("time:", t2)
}
}
Then start our service and access any interface to see the output as follows
This is the request first arrives at the middleware, and then arrives at our API interface. In the middleware, you can set the variable to the key of the Context, and then get the value in our API interface.
go
复制代码
r.GET("/", func(c *gin.Context) {
// 取值
req, _ := c.Get("request")
fmt.Println("request:", req)
// 页面接收
c.JSON(200, gin.H{"request": req})
})
At this time, you can see that the value set by the middleware is
next
The method is used in the middleware, which 后续中间件
means to execute the request processing (including the unexecuted middleware and the GET method processing we defined, if several middlewares are registered continuously, they will be executed in order of first-in-last-out. next就去执行下一个中间件里的next前面方法
.
go
复制代码
// 执行函数
c.Next()
// 中间件执行完后续的一些事情
partial middleware
Partial middleware means that some interfaces will take effect and only be used locally. At this time, visit http:127.0.0.1:8000/ to see the log printing of the middleware, and other API interfaces will not appear.
go
复制代码
//局部中间件使用
r.GET("/", MiddleWare(), func(c *gin.Context) {
// 取值
req, _ := c.Get("request")
fmt.Println("request:", req)
// 页面接收
c.JSON(200, gin.H{"request": req})
})
gin built-in middleware
go
复制代码
func BasicAuth(accounts Accounts) HandlerFunc
func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc
func Bind(val interface{}) HandlerFunc
func ErrorLogger() HandlerFunc
func ErrorLoggerT(typ ErrorType) HandlerFunc
func Logger() HandlerFunc
func LoggerWithConfig(conf LoggerConfig) HandlerFunc
func LoggerWithFormatter(f LogFormatter) HandlerFunc
func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc
func Recovery() HandlerFunc
func RecoveryWithWriter(out io.Writer) HandlerFunc
func WrapF(f http.HandlerFunc) HandlerFunc
func WrapH(h http.Handler) HandlerFunc
Summarize
Through custom middleware, we can easily intercept requests to do some things we need to do, such as logging, authorization verification, various filtering and so on.
Digression
In this first year of fast-growing technology, programming is like a ticket to a world of infinite possibilities for many people. In the star lineup of programming languages, Python is like the leading superstar. With its concise and easy-to-understand syntax and powerful functions, it stands out and becomes one of the most popular programming languages in the world.
The rapid rise of Python is extremely beneficial to the entire industry , but " 人红是非多
" has caused it to add a lot of criticism, but it still cannot stop its hot development momentum.
Will Python remain relevant and intact for the rest of the next decade? Today, we're going to analyze the facts and dispel some misconceptions.
If you are interested in Python and want to get a higher salary by learning Python, then the following set of Python learning materials must be useful to you!
Materials include: Python installation package + activation code, Python web development, Python crawler, Python data analysis, artificial intelligence, machine learning and other learning tutorials. Even beginners with 0 basics can understand and understand. Follow the tutorial and take you to learn Python systematically from zero basics!
1. Learning routes in all directions of Python
The route of all directions in Python is to organize the commonly used technical points of Python to form a summary of knowledge points in various fields. Its usefulness lies in that you can find corresponding learning resources according to the above knowledge points to ensure that you learn more comprehensively.
2. Python learning software
If a worker wants to do a good job, he must first sharpen his tools. The commonly used development software for learning Python is here!
3. Python introductory learning video
There are also many learning videos suitable for getting started with 0 basics. With these videos, you can easily get started with Python~
4. Python exercises
After each video lesson, there are corresponding practice questions, you can test the learning results haha!
Five, Python actual combat case
Optical theory is useless. You have to learn to type codes along with it, and then you can apply what you have learned in practice. At this time, you can learn from some practical cases. This information is also included~
6. Python interview materials
After we have learned Python, we can go out and find a job with the skills! The following interview questions are all from first-line Internet companies such as Alibaba, Tencent, and Byte, and some Alibaba bosses have given authoritative answers. After reading this set of interview materials, I believe everyone can find a satisfactory job.
7. Information collection
The full set of learning materials for the above-mentioned full version of Python has been uploaded to the CSDN official website. Those who need it can scan the QR code of the CSDN official certification below on WeChat to receive it for free.