network

OSI seven-layer model? Follow-up: Which layer is Socket on? Has WebSocket been used?

Internet protocols are divided into OSI seven layers, TCP/IP five layers or TCP/IP four layers according to their functions, as shown in the figure below:

A socket is an interface between the transport layer and the application layer. It hides the complex TCP/UDP protocol behind the Socket interface

Have not used, do the following understanding:

WebSocket is a new protocol for HTML5. It realizes full-duplex communication between browser and server, which can save server resources and bandwidth better and achieve real-time communication. It is built on TCP and transmits data through TCP as HTTP. However, the biggest difference between WebSocket and HTTP is that it is a two-way communication protocol.

IOS WebSocket long links

How do you understand layering and protocol?

A. How to understand layering

Reasons for layering:
  • The value of each layer accepts the specific services provided by the next layer and is responsible for providing the specific services for the upper layer. The conventions for the interaction between the upper and lower layers are called interfaces, and the conventions for the interaction between the same layer are called protocols. Each layer can be used independently, so that changes in some layers of the system will not affect the system.
  • Flexibility For any layer changes, as long as the upper and lower interfaces remain unchanged, will not cause system problems, conducive to the expansion and change of each layer function.
  • Ease of implementation and maintenance reduces large problems to small problems and large systems to small levels. For example, the communication process of the network is divided into smaller and simpler components, thus facilitating the development, design and troubleshooting of each component.
  • Enabling standardization efforts by layering, defining what functions are implemented at each layer of the model, helps encourage industry standardization while allowing multiple vendors to develop.
Principles of layering:
  • There are clear boundaries between the layers for easy understanding;
  • Each layer implements a specific function;
  • The division of levels is beneficial to the formulation of international standard agreements.
  • The number of layers should be sufficient to avoid duplication of functionality

B. How to understand the agreement

A protocol is actually a specification that both communication parties abide by. For example, if I need to pass gender and age to another host, I can define an “A protocol “where the first four bytes of data represent gender and the last four bytes represent age. This way the receiving host knows that the first four bytes are gender and does not mistake it for age.

The standardization and common compliance of the protocol is conducive to the communication and processing among different layers and the standardization process of the protocol.

How do routers and switches work, what protocols do they use, and on what layer are they located

Switch:

Layer 2 switch:

A Layer 2 switch is a network device that works at the data link layer and supports 802.1Q (VLAN), SNMP, rate limiting, broadcast storm control, ACL, and multicast. It has multiple ports to connect different devices. The switch determines which port to send data to according to the destination MAC address in each frame. In this case, the switch needs to refer to the forwarding table. The forwarding table is automatically learned by the switch. When a device sends a frame to the switch, the switch maps the source MAC address of the frame to the interface and adds it to the forwarding table. The following figure shows how the self-learning process works:

Layer 3 switch

Layer 3 switches function as routers. They work at the network layer and support routing protocols such as static routing, RIP(Vector Routing Protocol), OSPF(link State Routing Protocol), BGP(Border Gateway Protocol), and ISIS(Hierarchical link state Routing Protocol). Tunnel protocols such as MPLS, GRE, L2TP, and IPSec are required. Layer 3 switches can forward packet packets based on IP addresses.

Layer 4 to layer 7 switches

Responsible for processing data from the transport layer to the application layer in the OSI model. In terms of the TCP/IP layered model, layer 4-7 switches analyze data and perform specific processing based on the transport layer and the application layer above it.

For concurrent traffic, for example, a very large an enterprise Web site, use one server is not enough to meet the needs of the front end access, usually will fail server to share too much at this moment, the front-end server access entry address is usually only one (enterprise for the convenience of users, will only to the end user to open a unified access URL). To distribute front-end access to multiple backend servers using the same URL, you can add a load balancer to the front of each server. This load balancer is a layer 4-7 switch.

In addition, the actual communication, the hope is that when the network is congested, the priority of timeliness demanding such as voice communication requests, a bit slow processing such as email or data forwarding delay also unscathed communication request, this process is known as broadband control, is also the important function of the layer 4 to 7 switches, and many other functions, Examples include wide area network accelerators, special application access acceleration, and firewalls.

The router

The router works at the network layer and sends packet data to the target address through routing control. Supports routing protocols such as static routes, RIP(Vector Routing protocol), OSPF(link state Routing protocol), BGP(Border Gateway Protocol), EGP(external Gateway protocol), and ISIS(hierarchical link state routing protocol). The router stores the routing control table. It searches for the next router address corresponding to the destination IP address in the routing control table. This process is depicted below:

The IP address of host A is 10.1.1.30 and data is sent to host 10.1.2.10. In the routing table of host A, two fields are saved. Since the destination address 10.1.2.10 does not match segment 10.1.1.0/24, it is sent to the default route 10.1.1.1, which is the IP address of the left network card of Router 1 in the figure. Router 1 continues to look for the destination address 10.1.2.10 in its own routing control table. It finds that the destination address belongs to segment 10.1.2.0/24, so it forwards the data to the next router, 10.1.0.2, which is the address of the left network card on Router 2. Router 2 searches for destination IP address 10.1.2.10 in the routing control table and sends data to interface 10.1.2.1, that is, the IP address of the network adapter on the right of router 2. Host B checks that the destination IP address is the same as its own and receives data.

Interview questions [network]] (www.jianshu.com/p/5553ada4a)…

Introduce the differences between TCP and UDP. At which layer are they located?

TCP and UDP are located at layer 4 of the OSI seven-layer model: transport layer. The differences are as follows:

1, connectivity: TCP connection-oriented (such as making a phone call to establish a connection); UDP is connectionless, that is, no connection needs to be established before sending data. 2. Reliability: TCP provides reliable service. That is to say, data transmitted through the TCP connection is error-free, not lost, not repeated, and in order to arrive; UDP tries its best to deliver, but does not guarantee reliable delivery. 3, Transmission content: TCP byte stream oriented, in fact, TCP treats data as a series of unstructured byte streams; UDP is packet oriented and does not have congestion control. Therefore, network congestion does not reduce the sending rate of the source host (useful for real-time applications, such as IP phone calls and real-time video conferencing). UDP support one-to-one, one-to-many, many-to-one and many-to-many interactive communication 5, cost: TCP header cost 20 bytes; The header of UDP has a small overhead of only 8 bytes. 6. Channel The logical communication channel of TCP is a full-duplex reliable channel, while UDP is an unreliable channelCopy the code

Describes the process of TCP three-way handshake and four-way release.

TCP three-way handshake

  • First handshake: The client sets the SYN flag bit to 1, randomly generates a sequence value seq = X, and sends the packet to the server. The client enters the SYN_SENT state and waits for the server to confirm.

  • Second handshake: · After receiving the data packet, the server sets the flag bit SYN=1 and ACK = X + 1 to 1 when the client requests to establish a connection. The server randomly generates a value seq = Y and sends the data packet to the client to confirm the connection request. The server enters the SYN_RCVD state.

  • Third handshake:

    After receiving the acknowledgement, the client checks whether the ACK is X +1 and ACK is 1. If the ack bit is set to 1 correctly, ack = Y +1, and sends the packet to the server. The server checks whether the ACK is Y +1 and ACK is 1. The client and server enter the ESTABLISHED state, complete the three-way handshake, and then start data transmission between the client and server.

TCP waved four times

  • First wave: The clientA connectionRelease the packetAnd stop sending data. willRelease the data packet headertheFINSet to1.Serial number seqSet touEqual to the data already sentThe ordinal number of the last byte is incremented by 1) at this time,The clientEnter theFin-wait-1 (terminate WAIT 1)State.TCPRegulation,FINA message segment consumes an ordinal number even if it carries no data.
  • Second wave: The service sideAfter receiving the packet, check the headerFINfor1, knowThe clientrequestRelease the connection.The service sideaConfirmation messageAnd the header of the packetACKSet to1.ackSet tou + 1And bring your ownSerial number v, the server entersClose-wait (to CLOSE the WAIT state).The clientreceivedThe service sidetheConfirmation messageAfter the inspectionACKWhether it is1.ackWhether it isu+1If both are correct, the client entersFin-wait-2 (terminate WAIT 2)State. Waiting for theThe service sideSend the connectionRelease the packet.
  • Third wave: The service sideWhen the final data is sent, theThe clientSend the connectionRelease the packet.FIN=1.ack = u+1.The serial numberforseq = wSince the server is in the semi-closed state, it is likely to send some more dataThe serial numberforseq=wAt this time),The service sideEnter theLask-ack (Final confirmation)Status, waitingThe clientConfirmation.
  • Fourth wave: The clientreceiveThe serverAfter the packet is checkedFINfor1, knowThe service siderequestRelease the connection,Confirmation message.ACK = 1.ack = w + 1.seq = u + 1At this time,The clientEnter theTime-waitState. Notice The TCP connection is not released and must be passed2 ∗ MSL(Maximum Packet segment life) when the client revokes the correspondingTCBAfter enteringCLOSEDState.The service sideAs long as receivedThe clientIssued by theConfirmation messageTo checkACKWhether it is1.ackWhether it isw + 1If all are correct, enter immediatelyCLOSEState.

TCP three-way handshake process?

Combined with the TCP packet structure, it is clear:

1, TCP server process first create transmission control block TCB, always ready to accept the client process connection request, at this time the server enters the LISTEN state;

2. The TCP client process creates TCB and sends a connection request packet to the server. SYN=1 in the header of the packet and an initial sequence number seq= X is selected. According to TCP, the SYN segment (SYN=1) cannot carry data, but must consume a sequence number.

3. After receiving the request packet and agreeing to the connection, the TCP server sends an acknowledgement packet. In the acknowledgement packet, ACK=1, SYN=1, ACK= X +1, and seq= Y are initialized. Then, the TCP server process enters the SYN-RCVD state. This message also does not carry data, but again consumes a serial number.

4. The TCP client process also sends an acknowledgement to the server after receiving the acknowledgement. Confirm the ACK=1, ACK= y+1, and seq= X +1 of the packet. In this case, the TCP connection is ESTABLISHED and the client enters the ESTABLISHED state. According to TCP, AN ACK packet segment can carry data, but does not consume serial numbers if it does not.

5. After receiving the confirmation from the client, the server enters the ESTABLISHED state, and the two parties can communicate.

Reference:

[network related interview questions] (www.javazhiyin.com/35813.html)

TCP four wave process?

1. The client process sends a connection release packet and stops sending data. Release the header of the data packet, FIN=1, whose sequence number is SEq = U (equal to the sequence number of the last byte of the previously transmitted data plus 1). At this point, the client enters the fin-WaIT-1 state. According to TCP, FIN packets consume a sequence number even if they do not carry data.

2. After receiving the connection release packet, the server sends an acknowledgement packet with ACK=1, ACK= U +1, and its serial number seq= V. Then, the server enters the close-wait state. The TCP server notifies the higher-level application process that the client is released from the direction of the server. This state is half-closed, that is, the client has no data to send, but if the server sends data, the client still accepts it. This state also lasts for a period of time, i.e. the duration of the close-wait state.

3. After receiving the acknowledgement request from the server, the client enters the FIN-WaIT-2 state and waits for the server to send the connection release packet (before receiving the final data from the server).

After sending the final data, the server sends a connection release packet to the client. FIN=1, ACK = U +1. Because the server is in the half-closed state, it is likely to send more data.

5. After receiving the connection release packet from the server, the client must send ACK=1, ACK= W +1 and its serial number is SEQ = U +1. In this case, the client enters the time-wait state. Note that the TCP connection is not released at this time, and the client can enter the CLOSED state only after 2∗MSL (maximum packet segment life) and the corresponding TCB is revoked.

6. Once the server receives the confirmation from the client, it enters the CLOSED state immediately. Similarly, revoking the TCB terminates the TCP connection. As you can see, the server ends the TCP connection earlier than the client.

Reference:

Internet related interview questions

How to improve TCP

Adopt a confirmation mechanism

Is UDP full-duplex?

The so-called full duplex, half duplex, simplex refers to the connection oriented only some of the statement, if not connection oriented, there is no definite connection, how can there be a half duplex such as only one to come or one to go? UDP supports one-to-one, one-to-many, many-to-one and many-to-many interactive communication. If full duplex is involved at all, it means not only full duplex, but also full duplex service, but UDP is unreliable service.

Why wait for 2MSL?

MSL (Maximum Segment Lifetime) : TCP allows different implementations to set different MSL values. A, ensure that the client sends the final ACK packet to the server Because the ACK packet may be lost, standing in the server's perspective, I have already sent the FIN + ACK message request disconnect, the client also did not give me response, should be I send the request of the disconnect message it did not receive, then the server will send a again, The client receives the retransmitted message within the 2MSL period, responds with a message, and restarts the 2MSL timer. 2. Prevent the "invalid connection request message segment" mentioned in "three-way handshake" from appearing in this connection. After the client sends the last acknowledgement message, in this 2MSL time, all the message segments generated during the duration of the connection can be removed from the network. In this way, the new connection does not contain the request packets of the old connection.Copy the code

TCP/IP, 10 questions you must know and must know

Internet related interview questions

Why three handshakes to establish a connection, two is ok? What happens if the third handshake fails

A. Why the three-way handshake:

  • An error occurs in case an invalid connection request segment is suddenly sent to the server.
  • Because in network requests, we should always keep in mind that “network is unreliable and packets can be lost”.
  • Assuming there is no third confirmation,The clienttoThe service sideSend theSYNRequest to establish a connection. The server did not receive the packet in time due to delays. soThe clientResend oneSYNThe package. Recall the introductionThe TCP headerWhen mentionedThe serial numberThe serial numbers of the two bags are obviously the same.
  • Suppose the server receives itSecond SYN packetAfter a period of time, the communication ends and the connection is closed. That’s when it was first sentThe SYN packetJust arrived inThe service side.The service sideIt will be sent againACKConfirmation. Since two handshakes have established a connection, theThe service sideA new connection will be established, howeverThe clientYou don’t feel like you’re asking for a connection, so you don’tThe service sideSend data. Which leads toThe service sideAn empty connection is established and resources are wasted.
  • In the case of three handshakes,The service sideUntil receivedThe clientThe connection will be established after a response from. So in that case,The clientWill receive an identical oneACK packet, it will discard the packet and will notThe service sideA third handshake is avoidedThe service sideTo establishEmpty connection.

B. What if the handshake fails for the third time

  • In accordance with theTCP protocolThe general way to deal with packet loss,The service sideWill return to theThe clientsendThe packetUntil receivedACK to confirmSo far. But in practice this approach is likely to be metSYN flood attack. The so-calledFlood attacksRefers to theThe senderfakeMultiple IP addressesTo simulateThree-way handshakeIn the process. whenThe serverreturnACKAfter, the attacker deliberately do not confirm, so that the server constantly resendACK. Due to theThe serverBe in for a long timeSemi-connected stateAnd finally consume too muchCPUandMemory resourcesThe system freezes.
  • The right way to do it isThe service sidesendRST packetAnd into theCLOSEState. thisRSTA packet ofTCPIn the head, in the controlRST bitIs set to1. This meansThe connection informationAll initialized, originalTCPThe communication could not continue. If the client wants to re-establishTCPTo connect, you must restart the first handshake.

What do I do if the fourth handshake fails when I close the connection?

In fact, in step 3, when the client receives the FIN package, it sets a timer and waits for a considerable amount of time. If the ACK returned by the client is missing, the server also resends the FIN and resets the timer. Assuming that the FIN packet resent by the server does not reach the client before the timer expires, the client enters the CLOSE state, causing the server to never receive an ACK acknowledgement and thus cannot CLOSE the connection.

The schematic diagram is as follows:

Why TCP handshake three times, wave four times? (Assume the client is active and the server is passive)

In the TCP three-way handshake, the server sends the SYN and ACK packets on the same TCP segment to the client. During the disconnection, the server sends the ACK and FIN packets on different TCP segments to the client. This is because the server may have data to transmit after receiving the FIN from the client. Therefore, the server sends the ACK first, and then sends the FIN to disconnect the connection.

Why do you need three handshakes?

According to the fourth edition of Computer Networks, the purpose of the “three-way handshake” is “to prevent the invalid connection request message segment from suddenly being sent to the server and causing an error.”

The example in the book is as follows: “Invalid connection request segment” is generated when the first connection request segment sent by the client is not lost, but is delayed at a network node for a long time. As a result, it does not reach the server until a certain time after the connection is released. Originally, this is an invalid packet segment. However, after the server receives the invalid connection request packet segment, it mistakenly thinks it is a new connection request sent by the client. Then the client sends a confirmation message to agree to establish a connection.

Assuming that the “three-way handshake” is not used, a new connection is established as soon as the server sends an acknowledgement. Since the client does not send a connection request, it ignores the server’s confirmation and does not send data to the server. However, the server assumes that the new transport connection has been established and waits for data from the client. As a result, many of the server’s resources are wasted. The three-way handshake prevents this from happening. For example, the client does not issue an acknowledgement to the server’s acknowledgement. When the server receives no acknowledgement, it knows that the client has not requested a connection.” . The main purpose is to prevent the server from wasting resources by waiting.

Reference:

What happens from entering the URL to displaying the page

How does TCP ensure reliable transmission

○ Packet verification ○ Timeout retransmission mechanism ○ Reply mechanism ○ Reordering out-of-order packets ○ TCP also provides traffic controlCopy the code

How does TCP implement traffic control and congestion control?

A. How to control flow:

  • Flow controlTo dynamically adjust the sendSpace size (sliding window)In the form ofThe receiving endThe ability to receive messages, feedback toThe senderTo adjustSending speedTo avoidSending speedCaused by excessive speedPacket lossorToo slowReduces overall performance.
  • Here theSliding window mechanismFirst, it is not necessary to wait for the confirmation message to be received before continuing to send each time it is completed. Second, it is for referenceThe receiving endThe receiving capacity of theSending data segmentSize to avoid loss phenomenon.

B. How to control congestion:

  • At the beginning of the connection, ifwindowIs bigger,The senderA large amount of data may be sent suddenly, causing the network to crash. So, at the beginning of the communication,TCPthroughSlow startThe algorithm obtains the size of the window and controls the amount of data to be sent.

Flow control is controlled by both sender and receiver. We’ve just shown that the receiver writes the maximum window length it can handle in the TCP header, but there’s actually flow control on the sender, called congestion window. Windows in TCP are smaller values of sender and receiver Windows. The slow start process is as follows:

  • At the beginning of the correspondence,The sendertheCongestion windowSize of the1. Every time I receive oneACKAfter confirmation,Congestion windowDouble.
  • Due to theExponential growthVery quickly, very quicklyConfirm the packageTimeout. (Timeout is due to network congestion due to a large amount of data)
  • At this point, set aSlow Start ThresholdAnd its value is zeroThe current congested windowHalf the size.
  • At the same time willCongestion window sizeSet to1, re-enterSlow start process.
  • Because nowSlow Start ThresholdIt already exists whenCongestion windowSize toThe threshold valueWhen, instead of doubling, I’m going toA linear increase.
  • As thewindowSizes are increasing and may be receivedConfirm three timesAnswer, enter"Fast Retransmission"Phase. (Fast retransmission: whenThe senderThe continuous receivedThree repeated AcksIs the value ofData segmentIt has been lost and needs to be resent. When three entries representing the same data segment are receivedack, there is no need to wait for the timer to expire, i.e. resend the data segment (when the three ACKS reach the sender before the timeout), because it can be receivedThe receiving endThe ACK confirms the information, so the data segment is simply missing, not becauseNetwork congestionCause,)
  • At this time,TCPSlow Start ThresholdSet toCurrent congestion window sizeHalf of it, and thenCongestion window sizeSet toThreshold size(Also said to add 3).
  • Congestion windowAnd willA linear increaseUntil the next timeConfirm three timesReply ortimeout.

The above process can be summarized in the following figure:

Common HTTP status codes?

**1xx: Informational status code ** indicates that the server has received the client request and the client can continue to send the request

  • 100 Continue The original request has been accepted and the customer should Continue to send the rest of the request
  • The 101 Switching Protocols server converts compliance with a client’s request to another protocol

2XX: Success status code indicates that the server has successfully received and processed the request

  • 200 OK Indicates that the client request is successful
  • 204 No Content Is successful, but does not return the body of any entity
  • 206 Partial Content A Range request was successfully executed

3xx: Redirection status code indicates that the server requires client redirection

  • 301 Moved Permanently redirected Permanently. The Location header of the response packet should contain the new URL of the resource
  • 302 Found Temporary redirection. The URL in the Location header of the response packet is used to locate the resource temporarily
  • 303 See Other The requested resource has another URI. The client should use the GET method to obtain the requested resource
  • 304 Not Modified The server content is Not updated and can be read directly from the browser cache
  • 307 Temporary Redirect Temporary redirection. Same meaning as 302 Found. 302 Do not allow POST to be changed to GET, but this is not always the case. 307 More browsers may follow this standard, but it depends on the browser implementation

4xx: The client error status code indicates that the client request contains invalid content

  • 400 Bad Request Indicates that the client Request has syntax errors and cannot be understood by the server
  • 401 indicates that the request is unauthorized. This status code must be used with the WWW-Authenticate header field
  • 403 indicates that the server receives the request but refuses to provide the service. The reason is usually given in the response body
  • 404 Not Found The requested resource does Not exist, for example, an incorrect URL was entered

5XX: Server error status code Indicates that the server fails to properly process requests from clients and an unexpected error occurs

  • 500 Internel Server Error Indicates that an unexpected Error occurs on the Server. As a result, the client request cannot be completed
  • 503 indicates that the server cannot process client requests. The server may recover after a period of time

Reference:

Common HTTP Status Code description

What do you want to know, from entering the URL to displaying the page?

What happens from entering the URL to displaying the page?

The process for:

  • Your URL
  • The DNS
  • A TCP connection
  • Sending an HTTP request
  • The server processes the request
  • The server responds to requests
  • The browser parses and renders the page
  • End of the link

reference

What happens from entering the URL to displaying the page

What do you want to know, from entering the URL to displaying the page?

Another answer:

• Query DNS, Obtain the IP address corresponding to the domain name ○ Search the DNS cache of the browser ○ Search the DNS cache of the operating system ○ Read the HOST file of the local HOST ○ Initiate a DNS system call • View the cache of the broadband carrier server • Initiate an iterative DNS resolution request from the carrier server • After a TCP/IP connection is established, the browser can send an HTTP request to the server. • The server receives the request and, according to the path parameters, • The browser gets the complete HTML page code and starts parsing and rendering. If it encounters static resources such as external JS, CSS and images referenced, they are also HTTP requests. • The browser renders the page based on the resources it receives, and eventually renders a complete page to the userCopy the code

Internet related interview questions

What do you know about cookies?

The HTTP protocol does not persist requests and responses. Cookie technology was introduced for state management. Cookies are used to manage login state. Without cookies, HTTP does not save state and you must log in again every time you open a new web page.

The Cookie notifies the client to automatically save the Cookie based on the set-cookie field in the response packet. Cookies are automatically sent on the next request and the server compares the data to get a status result.

What do sessions and cookies do and how do they work?

Cookies (plural: Cookies) : Data (usually encrypted) stored on a user’s local terminal by some websites for identification and session tracking.

What it does: Because the HTTP protocol is stateless, meaning that the server does not know what the user did last time, this seriously hinders the implementation of interactive Web applications. In a typical online shopping scenario, the user browses through several pages and buys a box of cookies and two drinks. At the end of the checkout, due to the stateless nature of HTTP, the server does not know what the user has bought without additional means. To do this, you need to use cookies. Cookies can be set or read by the server to maintain state in the session between the user and the server.

The basic function of cookies is to store some information about a user’s visit to a website on the client side. Typical applications are

1, remember the password, the next automatic login

2. Shopping cart function

3. Record users’ browsing data and recommend products (advertisements)

Working principle:

1. Create a Cookie

The first time a user browses a web site that uses cookies, the site’s server does the following

1.1 The user generates a unique identification code (Cookie ID) and creates a Cookie object

1.2 By default, it is a session-level cookie stored in the browser’s memory and deleted after the user exits the browser. If the website wants the browser to store the Cookie on disk, it needs to set the maxAge and give a time in seconds (setting the maxAge to 0 commands the browser to delete the Cookie).

1.3 Insert Cookie into HTTP response header, insert Cookie into a set-cookie HTTP request header

1.4 Sending the HTTP Response Packet

2. Set cookies

After receiving the response packet, the browser generates the corresponding Cookie according to the special instructions of set-cookied in the packet header and saves it in the client. The Cookie records the user’s current information.

3. Send cookies

When the user visits the website again, the browser first checks all the stored Cookies. If there is a Cookie existing on the website (that is, the declared scope of the Cookie is greater than or equal to the resource to be requested), the Cookie is attached to the HTTP request head of the requested resource and sent to the server

4. Read the Cookie

After receiving the USER’s HTTP request packet, the server obtains the user’s Cookie from the packet header and finds what it needs

Session: Represents a Session between the server and the browser. This Session can be continuous or intermittent. Session is a server-side mechanism where Session objects are used to store information needed for a particular user’s Session

How it works: Create a session and use a session. See the reference URL for details

Purpose: The basic purpose of the Session is to store some information about the user and server Session on the server side

1. Check whether the user has logged in

2. Shopping cart function

Reference:

The functions and working principles of cookies and sessions

Talk about the understanding of 5G technology?

To put it simply, 5G is the fifth generation of communication technology, which is mainly characterized by millimeter wavelength, ultra-broadband, ultra-high speed and ultra-low delay.

If 5G is to achieve high end-to-end speed, the key is to break through the bottleneck of wireless.

Light speed = wavelength * frequency

To achieve more efficient transmission rates, shorter waves must be used. 5G uses millimeter waves (1-10 mm).

The significant characteristics of electromagnetic wave: the higher the frequency, the shorter the wavelength, the more inclined to linear propagation (diffraction and wall penetration ability is worse). **** The higher the frequency, the greater the attenuation in the propagation medium.

So 5G requires a lot of microbase stations. It is good for human body and reduces radiation.

It’s the first time anyone’s talked about 5G in such a straightforward way

What if the connection has been established, but the client suddenly fails?

TCP also has a keepalive timer, so obviously if the client fails, the server can’t wait forever and waste resources. The server resets this timer every time it receives a request from the client, usually for two hours. If it does not receive any data from the client within two hours, the server sends a probe segment, which is then sent every 75 minutes. If there is no response after 10 probe packets are sent, the server assumes that the client is faulty and closes the connection.

Internet related interview questions

What’s the difference between Http and Https?

1. Security: HTTP is HTTP protocol running on top of TCP. All transmitted content is in plain text, and neither the client nor the server can verify the identity of the other. HTTPS is HTTP running on top of SSL/TLS and SSL/TLS running on top of TCP. All transmitted content is encrypted using symmetric encryption, but the symmetric encryption key is asymmetrically encrypted using the certificate of the server. In addition, the client can authenticate the server. If client authentication is configured, the server can also authenticate the client. 2. Certificate HTTPS requires you to apply for a certificate from a CA. Generally, a few free certificates need to be paid. 3. Transport protocol HTTP is a hypertext transmission protocol, and information is transmitted in plain text. HTTPS is a secure SSL encryption transmission protocol. Port HTTP and HTTPS use completely different connections and use different ports, 80 for HTTP and 443 for HTTPS.Copy the code

Principle of HTTPS?

HTTPS is actually composed of two parts: HTTP + SSL/TLS, that is, on top of HTTP, another layer of modules for processing encrypted information. Both the server and client are encrypted through TLS. Therefore, the transmitted data is encrypted.

HTTPS is HTTP based on the SSL/TLS security protocol.

In iOS, the client stores the CA certificate locally. In AN HTTPS request, the client first asks for the public key from the server. After obtaining the public key, the client uses the local CA certificate to verify the public key and sends the encrypted information to the server.

HTTPS has a lower performance than HTTP because SSL/TLS has several handshakes and encryption and decryption processing, but encryption and decryption processing can already be accelerated by special hardware.

1. The client initiates an HTTPS request. The user enters an HTTPS url in the browser and connects to port 443 of the server. 2. Configure the server. The HTTPS server must have a digital certificate, which can be created by yourself or applied for from an organization. The difference is that your certificate needs to be verified by the client before you can continue to access it, while certificates applied by trusted companies do not pop up a prompt page (StartSSL is a good choice, with a one-year free service). The certificate is a pair of public and private keys. If the public and private keys is not very understanding, can imagine as a key and a locks, but the world only you a man who had the key, you can put the locks to others, other people can use this lock lock important things up, and then sent to you, because only you a man who had the key, so only you can see things this lock lock up. The certificate is actually a public key, but contains a lot of information, such as the certificate authority, expiration date, and so on. 4. The client resolves the certificate through TLS. First, the client verifies whether the public key is valid, such as the issuing authority and expiration time. If there is nothing wrong with the certificate, a random value is generated. The random value is then encrypted with a certificate. As mentioned above, the random values are locked so that unless you have a key, you can't see what is locked. 5. Transmission of encrypted information This part transmits the random value encrypted with the certificate. The purpose is to let the server get the random value, so that the communication between the client and the server can be encrypted and decrypted by the random value. 6. Service segment decryption information After decrypting with the private key, the server gets the random value (private key) sent by the client, and then encrypts the content symmetrically through the value. Symmetric encryption is the mixing of information and the private key through some algorithm, so that unless you know the private key, you can't get the content, and both the client and the server know the private key, so as long as the encryption algorithm is strong enough, the private key is complex enough, the data is secure enough. 7. Transmission of encrypted information This part of the information is encrypted with the private key of the service segment, which can be restored on the client. Client decrypts information The client decrypts the information sent by the service segment using the previously generated private key, and then obtains the decrypted content. Even if the third party listens to the data, there's nothing they can do about it.Copy the code

How HTTPS works

The HTTPS principle of the Simple and rude series

21 – Principles of HTTPS and SSL Certificates

What is the difference between GET and POST in HTTP requests?

  1. GET uses a URL or Cookie to pass parameters, while POST puts data in the BODY because of the convention of HTTP protocol usage. Not in themselves.
  2. The data submitted by GET is limited in length, while the data submitted by POST can be very large due to the differences in operating system and browser Settings. It’s not the difference between GET and POST per se.
  3. POST is safer than GET because the data is not visible in the address bar, which is fine, but still not the difference between GET and POST per se.
  4. The main difference is that GET requests are idempotent, whereas POST requests are not

HTTP | GET and POST? Most of the answers online are wrong!

Another answer:

• Browsers have limits on the length of urls, So GET requests can't send a lot of data instead of POST requests • GET requests send less data • GET requests are insecure • GET requests are idempotent • POST requests can't be cached • POST requests are "secure" relative to GET requests • In the following cases, Please use POST request: 1. Unable to use cached files (update files or databases on the server) 2. Send large amounts of data to the server (POST has no data limit) 3. POST is more stable and reliable than GET when sending user input containing unknown characters. 4. POST is more secure than GETCopy the code

Online Interview questions

What’s the difference between Session and Cookie?

HTTP is a stateless connection, and every time a client reads a Web page, the server thinks it’s a new session. But sometimes we need to keep some information, such as the user name and password when logging in, and the information when the user was connected last time. This information is stored by cookies and sessions. The fundamental difference between the two is that cookies are stored on the client, while sessions are stored on the server. From this, we can also develop the following conclusions:

  • cookieRelatively insecure, browsers can parse localcookieforcookieDeception.
  • sessionYou can set the timeout period, after this time, the invalid, so as not to occupy for a long timeThe service sideMemory.
  • A singlecookieThe size is limited(4 Kb), for each sitecookieQuantity is also generally limited(20).
  • The clientEvery time I putcookieSent to theThe service side, soThe service sideYou can knowcookie, butThe clientI don’t knowsession.

When the server receives the cookie, it will find the client session according to the SessionID in the cookie. If not, a new SessionID is generated and sent to the client.

What is your understanding of HTTP 1.1, 2.0 and HTTPS?

A, the HTTP

HyperText Transfer Protocol (HTTP) is an application-layer Protocol that is widely used on the Internet.

It is designed for communication between Web browsers and Web servers, but it can also be used for other purposes. HTTP follows the classic client-server model, where a client opens a connection to make a request and then waits for it to receive a server-side response. HTTP is a stateless protocol, meaning that the server does not retain any data (state) between requests.

HTTP1.0 — Build scalability

HTTP 1.0 stipulates that the browser and the server only maintain a short connection, each browser request needs to establish a TCP connection with the server, the server immediately disconnects the TCP connection after the completion of the request processing, the server does not track each client and does not record past requests.

Three,HTTP1.1— Standardized protocols

The many different implementations of HTTP/1.0 can be confusing to use. HTTP1.1 is the first standardized release that focuses on correcting structural flaws in the HTTP1.0 design:

  • The connection can be reused, saving the time it takes to open it multiple times to display resources embedded in a single original document.
  • Add pipelined operations that allow a second request to be sent before the first reply has been fully sent to reduce communication latency.
  • Supports response chunking.
  • Introduce additional cache control mechanisms.
  • Introduce content negotiation, including language, encoding, or type, and allow client and server conventions to exchange the most appropriate content.
  • Add the Host header so that different domain names can be configured on the same IP address of the server.
  • Security has been improved

Connection :close; connection:close; connection:close;

HTTP2.0 — For better performance

HTTP/2.0 differs from HTTP/1.1 in several basic ways:

  • HTTP2isBinary protocolRather thanText protocol. No longer readable and barrier-free by manual creation, improved optimization techniques can now be implemented.
  • This is a multiplexing protocol. Parallel requests can be processed within the same link, removing the order and blocking constraints of HTTP/1.x.
  • I’m compressing headers. Because Headers is often similar across a series of requests, it removes duplication and the cost of transferring duplicate data.
  • It allows the server to populate the client cache with data requested in advance through a mechanism called server push.

Five, the HTTPS

We know that HTTP uses TCP directly for data transmission. Data is transmitted in plaintext without encryption. Therefore, there are three risks:

  • Risk of eavesdropping: Third party nodes can learn the contents of communications.
  • Tamper risk: Third-party nodes can modify communication content.
  • Impersonation risk: Third-party nodes can impersonate others to participate in communication.

For example, when you open a web page in an app on your phone, you sometimes see ads pop up at the bottom of the page, which in effect means that your HTTP content has been bugged and tampered with. The HTTPS protocol is designed to address these three risks, so it can:

  • Ensure that all information is encrypted and cannot be stolen by third parties.
  • Add a verification mechanism for information so that it can be detected if it is maliciously damaged by a third party.
  • Equipped with an identity certificate to prevent third parties from participating in communication in disguise.

The structure of HTTPS looks like this:

It simply adds a TLS/SSL layer between HTTP and TCP, confirming the adage that “all computer problems can be solved by adding an intermediate layer”. When HTTPS is used, the server sends its certificate to the client, which contains the public key of the server. The transmission process based on asymmetric encryption is as follows:

  • The client uses the public key to encrypt the information and sends the ciphertext to the server
  • The server decrypts it with its own private key and sends the returned data back to the client encrypted with the private key
  • The client decrypts using the public key

The certificate here is a tool for the server to prove its identity and is issued to the applicant by an authoritative certificate authority (CA). If the certificate is fake, or if it is a self-issued certificate, the server will disrecognize the certificate and issue a warning:

To summarize how THE HTTPS protocol avoids the three risks mentioned above:

  • Use firstAsymmetric encryptionTransfer the password, and then use the password symmetryEncrypt the data, so that the third party cannot obtain the communication content
  • The senderThe data ofHash resultWrite to the data,The receiving partyDecrypted and compared the dataHash resultIf they are inconsistent, they are modified. Because the transmitted data is encrypted, a third party cannot modify the hash result.
  • byIssued by authorityCertificate, plusCertificate of calibrationMechanism to avoidThird party disguiseParticipate in correspondence.

Network level questions

Why is it three handshakes to establish a connection, but four waves to close it?

This is because in LISTEN state, the server receives a SYN packet for establishing a connection and sends the ACK and SYN packets to the client. And close the connection, when I received the other side of the FIN message just said to each other can no longer send data but also receives the data, the board may not all data are sent to each other, so their can immediately close, also can send some data to each other, then send the FIN message now agreed to close the connection to the other side, therefore, Your ACK and FIN are usually sent separately.

Reference:

What happens from entering the URL to displaying the page