Interviewer: How do you understand the OSI seven-layer model and the TCP/IP four-layer model?
2025.05.06
1. Interviewer: What is the OSI seven-layer model? What is the role of each layer? What is the difference between the TCP/IP four-layer model and the OSI seven-layer model?
The OSI (Open Systems Interconnection) seven-layer model is a layered model used to understand and implement network communications. It divides the network communication process into seven independent functional layers. Each layer focuses on completing specific tasks and provides services to the upper layer while relying on the support of the next layer. The following is a detailed description of the OSI seven-layer model and the role of each layer:
1. Application Layer
Function: The application layer is the highest layer of the OSI model, interacting directly with users and providing network services and application interfaces.
Key functions:
Provide an interface for users to access network resources.
Supports functions such as file transfer, e-mail, and remote login.
Typical protocols: HTTP (Hypertext Transfer Protocol), FTP (File Transfer Protocol), SMTP (Simple Mail Transfer Protocol), DNS (Domain Name System).
2. Presentation Layer
Function: The presentation layer is responsible for data format conversion, encryption, and compression to ensure that data can be correctly interpreted between different systems.
Key functions:
Data encoding and decoding (such as ASCII, EBCDIC).
Data encryption and decryption (such as SSL/TLS).
Data compression and decompression.
Typical protocols: SSL/TLS.
3. Session Layer
Function: The session layer is responsible for establishing, managing, and terminating sessions (communication sessions) between applications.
Key functions:
Control the establishment, maintenance, and disconnection of sessions.
Provide session synchronization and checkpoint functions (such as breakpoint resumption).
Typical protocols: NetBIOS, RPC (Remote Procedure Call), PPTP (Point-to-Point Tunneling Protocol).
4. Transport Layer
Function: The transport layer is responsible for end-to-end communication, ensuring that data is transmitted from the source host to the target host in a complete and orderly manner.
Key functions:
Provide reliable data transmission (such as TCP) or unreliable data transmission (such as UDP).
Implement flow control and error recovery.
Data segmentation and reassembly.
Typical protocols:
TCP (Transmission Control Protocol): connection-oriented, reliable transmission.
UDP (User Datagram Protocol): connectionless, fast but unreliable.
5. Network Layer
Function: The network layer is responsible for packet routing and forwarding to ensure that data can reach the target host from the source host.
Key functions:
Provide logical addresses (such as IP addresses).
Routing and packet forwarding.
Segment and reassemble packets.
Typical protocols/equipment:
Equipment: Router.
Protocol: IP (IPv4/IPv6), ICMP, ARP.
6. Data Link Layer
Function: The data link layer is responsible for reliably transmitting data frames between adjacent nodes and handling errors (such as bit errors) that may be introduced by the physical layer.
Key functions:
Encapsulate bit streams into frames.
Implement flow control and error detection and correction.
Define MAC addresses (media access control addresses) to identify devices.
Typical protocols/equipment:
Equipment: switches, bridges.
Protocols: Ethernet, PPP (Point-to-Point Protocol), HDLC.
7. Physical Layer
Function: The physical layer is responsible for transmitting the original bit stream (0 and 1) on the physical medium. It defines the electrical, mechanical, functional and procedural characteristics between hardware devices (such as network cards, cables, etc.).
Key functions:
Define voltage, interface, cable standards, etc.
Realize the transmission and reception of bit streams.
Provide the establishment, maintenance and release of physical connections.
Typical protocols/equipment:
Equipment: Repeater, Hub
The OSI seven-layer model decomposes complex network communication tasks into multiple independent functional modules through a layered approach. Each layer focuses on completing specific tasks and provides support for the upper layer. This layered design allows different network protocols and devices to work together to achieve cross-network communication.
The upper three layers (application layer, presentation layer, session layer) are closer to users and are responsible for providing advanced network services and data processing functions.
The lower three layers (transmission layer, network layer, data link layer, physical layer) are mainly responsible for the basic part of network communication, including data transmission, routing and link management.
8. TCP/IP four-layer model
From bottom to top, it is divided into four layers:
Network interface layer: corresponds to the physical layer and data link layer of OSI, responsible for hardware-related data transmission.
The OSI seven-layer model is more suitable for learning and understanding the basic principles of network communication, while the TCP/IP four-layer model has become the actual standard for modern network communication due to its efficiency and practicality.
2. Interviewer: HTTP itself is a stateless protocol. How does HTTP save user status?
HTTP is a stateless protocol, which means that each request and response are independent of each other, and the server will not automatically save the user's session status. However, in actual applications, in order to save user status (such as login status, shopping cart information, etc.), the following mechanisms are usually used:
1. Use Cookies
Principle: The server stores the user's status information on the client by setting the Set-Cookie field in the HTTP response header. The client will automatically carry the cookie in subsequent requests to achieve status transmission.
Example:
Set Set-Cookie: sessinotallow=abc123; Path=/; HttpOnly when the server returns the response.
The client will add Cookie: sessinotallow=abc123 to the request header in the next request.
Advantages:
Easy to use, suitable for saving small amounts of data.
Supports security features such as expiration time and domain restrictions.
Disadvantages: Data is stored on the client and may be tampered or stolen (need to be used with encryption or signature).
2. Use Session
Principle: The server generates a unique session ID for each user and sends it to the client through Cookie or URL rewriting. The actual user status information (such as login information) is stored on the server, and the client only saves the Session ID.
Example:
After the user logs in, the server generates a Session and returns Set-Cookie: sessinotallow=xyz456.
The client carries Cookie: sessinotallow=xyz456 in subsequent requests, and the server retrieves the corresponding user status based on the ID.
Advantages:
Sensitive data is stored on the server side, which is more secure.
Reduce the data storage burden on the client side.
Disadvantages: The server needs to maintain a large amount of session data, which may lead to performance bottlenecks.
3. Use Token (such as JWT)
Principle: After the user successfully logs in, the server generates a token and returns the token to the client. The client carries the token in the request header (such as Authorization: Bearer) in subsequent requests. The server identifies the user status by verifying the legitimacy of the token.
JWT example:
Token format: Header.Payload.Signature, where Payload contains user information (such as user ID, role, etc.).
The client sends a request with Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9….
Advantages:
No need for the server to store session information, supporting distributed deployment.
Token can contain custom data, reducing database queries.
Disadvantages:
Tokens are large, increasing the cost of each request.
Once a token is issued, it cannot be easily revoked (a blacklist mechanism needs to be introduced).
4. URL rewriting
Principle: Append user status information (such as session ID) to the URL and pass it to the server as part of the request.
Example:
URL returned by the server: http://example.com/cart?sessinotallow=12345.
When the client clicks the link, the session ID is sent to the server along with the URL.
Advantages: Does not rely on cookies, suitable for scenarios where cookies are disabled.
Disadvantages:
Status information is exposed in the URL, which poses a security risk.
The URL length is limited and is not suitable for storing complex data.
5. Hidden form fields
Principle: Embed hidden fields in HTML forms to store user status information. When the user submits the form, this information will be sent to the server along with the request.
Example:
Copy
<input type="hidden" name="sessionId" value="abc123">
1.
Advantages: Simple and easy to implement, suitable for specific scenarios.
Disadvantages:
Only applicable to POST requests, cannot overwrite all interactive scenarios.
Low security, easy to be tampered with.
6. Summary
To sum up, although the HTTP protocol itself is stateless, it can effectively save the user status through the above mechanisms (such as Cookie, Session, Token, etc.) to meet the needs of different scenarios.
3. Interviewer: Can you explain in detail the working principle, life cycle, and scope of cookies? What are the limitations of using cookies to store session information?
Cookies are small text files used between browsers and servers to store user session information. The working principle of cookies involves multiple links, including creation, storage, transmission, update, and security measures. The following is a detailed introduction to the working principle of cookies:
1. Creation and setting of cookies
When a user visits a website for the first time, the server can create a cookie through the Set-Cookie instruction in the HTTP response header. This instruction contains the name, value, and some optional attributes of the cookie.
For example:
Key-value pair: sessinotallow=abc123 means the name of the cookie is sessionId and the value is abc123.
Scope: Path=/ means this cookie is valid in all paths of the entire website.
Security:
HttpOnly prohibits JavaScript from accessing this cookie, which helps prevent cross-site scripting attacks (XSS).
Secure means this cookie can only be transmitted via the HTTPS protocol, which helps prevent man-in-the-middle attacks.
Lifecycle: Max-Age=3600 means this cookie expires after 3600 seconds (1 hour).
2. Cookie storage and management
The browser stores cookies according to the domain name and path rules. Cookies under each domain are stored independently, for example, the cookies of example.com and other.com are stored separately. The scope of the cookie is determined by the Path attribute, for example, the cookie with Path=/shop is only valid under the /shop path.
The browser also manages the life cycle of the cookie according to the expiration time of the cookie (Max-Age or Expires attribute). If the cookie does not set an expiration time, it is a session cookie and will be automatically deleted after the browser is closed. If an expiration time is set, it is a persistent cookie and will expire after the specified time.
3. Automatic carrying and use of cookies
When a user visits the same website again, the browser will automatically attach the relevant cookies to the HTTP request header and send it to the server. For example:
The server can identify the user's identity by parsing the cookie information in the request header, thereby realizing functions such as session management and personalized services.
For example:
Session management: The server can use sessionId to identify whether the user is logged in, so that the user does not need to log in again every time.
Personalized service: The server can provide customized content based on the user preferences (such as language, theme, etc.) stored in the cookie.
4. Update and delete cookies
The server can update the value or attributes of the cookie by sending the Set-Cookie command again. For example, the server can extend the validity period of the cookie or modify the scope of the cookie.
To delete a cookie, the server can send a cookie with the same name and set its expiration time to a time that has passed. For example:
5. Cookie security and limitations
Although cookies are very useful in web development, they also face some security risks:
Cross-site scripting attacks (XSS): If the cookie does not set the HttpOnly attribute, malicious scripts may steal information in the cookie.
Cross-site request forgery (CSRF): Attackers can use cookies to forge user requests.
In addition, cookies have some limitations:
Size limit: The size of a single cookie usually cannot exceed 4KB.
Quantity limit: The number of cookies that can be stored under each domain is limited.
6. Cookie alternatives
With the development of Web technology, cookies are no longer the best choice in some scenarios. Here are some alternatives to cookies:
LocalStorage/SessionStorage: Local storage solutions provided by HTML5, with larger capacity (usually 5-10MB), but limited to client use.
Token authentication: Using tokens such as JWT (JSON Web Token) to replace cookies can reduce server storage pressure and improve security.
7. Summary
Cookies achieve the persistence of user status through the mechanism of server creation, browser storage and automatic portability. It plays an important role in session management, personalized services, etc., but developers also need to pay attention to its security and limitations, and choose a suitable storage solution according to actual needs.
IV. Interviewer: What is the difference between Session and Cookie? If there is no Cookie, can Session still be used? How to implement Session-Cookie solution under multiple server nodes?
1. Detailed explanation of how sessions work
Sessions are similar to cookies and are also an important mechanism for tracking user status in Web development. They allow the server to identify and remember specific users between multiple requests, thereby achieving personalized user experience and secure user authentication.
The following are the detailed steps of how sessions work:
(1) Session creation
User's first visit: When a user visits the server for the first time, the server will create a new Session object. This process is usually completed automatically by the server-side programming language and framework, without the need for manual intervention by the developer.
Generate Session ID: The server assigns a unique identifier to the Session object, called the Session ID. This ID is usually a randomly generated string used to identify and retrieve the corresponding Session object in subsequent requests.
Transmit Session ID: The server transmits the Session ID to the client in some way, usually by storing it in the user's browser, such as as a cookie value or as a parameter in the URL.
(2) Session storage
Server-side storage: Session objects are usually stored in the server's memory, but can also be stored elsewhere, such as databases, file systems, etc. The storage method depends on the server configuration and application requirements.
Memory storage: Fast, but data may be lost when the server is restarted or memory is insufficient.
Database storage: Strong persistence, supports session sharing and clustering, but relatively slow.
File system storage: Simple, but slow, not conducive to session sharing.
(3) Session transmission and use
The client carries the Session ID: In the user's subsequent requests, the browser will automatically send the Session ID (usually through cookies) to the server.
Server verifies the Session ID: The server searches for the corresponding Session object based on the Session ID sent by the client. If found, the server loads the user's session data.
Read and write Session data: The server reads or modifies the user's Session data based on the current request to complete various business logic processing, such as saving the user's login status, shopping cart content, etc.
(4) Destruction of Session
Session end: When a session ends, the server will destroy the corresponding Session object to release occupied resources. Session end situations include the user closing the browser, session timeout, user active logout, etc.
Timeout setting: The server can set a session timeout. When the user is inactive for a period of time, the server will automatically destroy the Session object.
Active destruction: When the user actively logs out, the server should destroy the corresponding Session object to ensure the user's privacy and security.
2. Web page source code example (Node.js + Express)
3. The key differences between Session and Cookie are as follows:
In a multi-server node environment, the core issue that needs to be solved when implementing the Session-Cookie solution is Session sharing and synchronization, ensuring that the session status remains consistent when users switch between different servers. The following are the specific solutions and implementation steps:
1. Session sharing and synchronization mechanism
(1) Sticky Session
Principle: All requests from the same user are fixedly assigned to the same server through a load balancer (such as Nginx).
Example of configuration (Nginx):
Disadvantages:
Server load may be unbalanced.
Failure of a single server may cause user session loss.
(2) Session replication
Principle: Real-time synchronization of session data between servers to ensure that all servers have the same session information.
Implementation:
The Tomcat cluster is configured with Cluster nodes and DeltaManager.
Spring Session integrates cache servers such as Redis.
Disadvantages:
High network bandwidth consumption.
High coupling between servers.
(3) Shared storage
Principle: Store session data in shared storage (such as database, cache server, file system), and all servers access it through a unified interface.
Technology selection:
Database MySQL (persistent storage, but low performance).
Cache server Redis (high performance, supports expiration time).
File system NFS (simple and easy to use, but low performance).
2. Specific implementation steps (taking Redis as an example)
(1) Technology selection
Redis: As a shared storage, it provides high-performance session reading and writing.
Spring Boot: Integrates Spring Session to simplify development.
(2) Configuration steps
Add dependencies:
Redis configuration:
Enable Spring Session:
(3) Code examples
Store Session:
Read Session:
4. Summary