Network (8)

79. What do the http response codes 301 and 302 represent? What's the difference?

Answer: 301 and 302 are the encoding of HTTP status, which means that a certain URL has been transferred.

the difference:

  • 301 redirect: 301 stands for Permanently Moved.
  • 302 redirect: 302 stands for Temporarily Moved.

80. The difference between forward and redirect?

Forward and Redirect represent two request forwarding methods: direct forwarding and indirect forwarding.

Direct forwarding mode (Forward), the client and browser only send a request once, Servlet, HTML, JSP or other information resources, the second information resource responds to the request, in the request object request, the saved object is for each information Resources are shared.

The indirect forwarding method (Redirect) is actually two HTTP requests. When the server responds to the first request, the browser sends a request to another URL to achieve the purpose of forwarding.

Give a popular example:

Direct forwarding is equivalent to: "A asks B to borrow money, B says no, B goes to C to borrow, and if it fails to borrow, it will pass the message to A";

Indirect forwarding is equivalent to: "A asks B to borrow money, B says no, let A go to C to borrow."

81. Briefly describe the difference between tcp and udp?

  • TCP is connection-oriented (such as dialing to establish a connection before making a call); UDP is connectionless, that is, no connection is required before sending data.
  • CP provides reliable services. That is to say, the data transmitted through the TCP connection has no errors, no loss, no duplication, and arrives in order; UDP does its best to deliver, that is, reliable delivery is not guaranteed.
  • cp realizes reliable transmission through checksum, retransmission control, serial number identification, sliding window, and confirmation response. For example, the retransmission control when the packet is lost, the sequence control of the out-of-sequence sub-packets can also be performed.
  • UDP has better real-time performance, higher work efficiency than TCP, and is suitable for high-speed transmission and real-time communication or broadcast communication.
  • Each TCP connection can only be point-to-point; UDP supports one-to-one, one-to-many, many-to-one and many-to-many interactive communications.
  • TCP requires more system resources, while UDP requires less system resources.

82. Why does tcp need to shake hands for three times, can't it work twice? why?

In order to achieve reliable data transmission, both parties in the TCP protocol must maintain a sequence number to identify which of the sent data packets have been received by the other party. The process of the three-way handshake is a necessary step for the communicating parties to inform each other of the initial value of the serial number and confirm that the other party has received the initial value of the serial number.

If there are only two handshakes, at most only the initial sequence number of the initiator of the connection can be confirmed, and the sequence number selected by the other party cannot be confirmed.

83. Tell me about how tcp sticky packets are generated?

①. The sender generates a sticky package

The client and server that use the TCP protocol to transmit data often maintain a long connection state (there is no sticky packet when the data is sent once a connection), and the two parties can always transmit data when the connection is not disconnected; but when the data packet is sent If it is too small, then the TCP protocol will enable Nagle algorithm by default to combine and send these smaller data packets (buffer data transmission is a process of heap compression); this combination process is carried out in the sending buffer, and That is to say, when the data is sent out, it is already in a sticky state.

Insert picture description here
②. The receiver generates a sticky package

When the receiver uses the TCP protocol to receive data, the process is like this: the data is passed to the transport layer from below the network model to the receiver. The TCP protocol processing of the transport layer places it in the receiving buffer, and then the application layer actively obtains it. (C language uses recv, read and other functions); at this time there will be a problem, that is, the read data function we call in the program can not take out the data in the buffer in time, and the next data comes and has a part The end of the put buffer is a sticky packet when we read the data. (The speed of putting data> the speed of taking data at the application layer)Insert picture description here

84. What are the seven-layer models of OSI?

  • Application layer: an interface between network services and end users.
  • Presentation layer: data presentation, security, and compression.
  • Session layer: establish, manage, and terminate sessions.
  • Transport layer: Define the protocol port number for data transmission, as well as flow control and error checking.
  • Network layer: Perform logical address addressing to realize path selection between different networks.
  • Data link layer: functions such as establishing logical connections, addressing hardware addresses, and error checking.
  • Physical layer: establish, maintain, and disconnect physical connections.

85. What is the difference between get and post requests?

GET is harmless when the browser rolls back, while POST will submit the request again.

  • The URL address generated by GET can be Bookmarked, but not by POST.
  • GET requests will be actively cached by the browser, while POST will not, unless manually set.
  • GET requests can only be url-encoded, while POST supports multiple encoding methods.
  • GET request parameters will be completely retained in the browser history, while POST parameters will not be retained.
  • The parameters transmitted in the URL of a GET request are limited in length, but not for POST.
  • The data type of the parameter, GET only accepts ASCII characters, and POST has no restrictions.
  • GET is less secure than POST, because parameters are directly exposed on the URL, so it cannot be used to transmit sensitive information.
  • GET parameters are passed through the URL, and POST is placed in the Request body.

86. How to achieve cross-domain?

Method 1: Image ping or script tag cross-domain

Picture pings are often used to track the number of user clicks on pages or dynamic ad exposures.
Script tags can get data from other sources, which is also the basis for JSONP's reliance.

Method 2: JSONP cross-domain

JSONP (JSON with Padding) is a "use mode" of the data format JSON, which allows web pages to request data from other domains. According to the XmlHttpRequest object is affected by the same-origin policy, and use

  • Can only use Get request
  • It is not possible to register event monitoring functions such as success and error, and it is not easy to determine whether the JSONP request failed
  • JSONP is executed by loading code from other domains. It is vulnerable to cross-site request forgery attacks, and its security cannot be guaranteed.

Method 3: CORS

Cross-Origin Resource Sharing (CORS) is a browser technology specification that provides a method for Web services to send sandbox scripts from different domains to avoid the browser’s same-origin policy and ensure safe cross-origin Domain data transmission. Modern browsers use CORS in API containers such as XMLHttpRequest to reduce the risk of HTTP requests. Unlike JSONP, CORS also supports other HTTP requirements in addition to the GET request method. The server generally needs to add one or more of the following response headers:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER, Content-Type
Access-Control-Max-Age: 86400

12345

Cross-domain requests will not carry cookie information by default. If you need to carry it, please configure the following parameters:

"Access-Control-Allow-Credentials": true
// Ajax设置
"withCredentials": true

1234

Method 4: window.name+iframe

window.name works by loading a cross-domain HTML file in an iframe (generally dynamically created i). Then, the HTML file assigns the string content passed to the requester to window.name . The requester can then retrieve the window.name value as a response.

  • Cross-domain capabilities of iframe tags;
  • The ability of the indow.name attribute value to still exist after the document is refreshed (and the maximum allowable is about 2M).

Each iframe has a window that wraps it, and this window is a child window of the top window. The contentWindow attribute returns the Window object of the element. You can use this Window object to access the iframe document and its internal DOM.

<!-- 
 下述用端口 
 10000表示:domainA
 10001表示:domainB
-->

<!-- localhost:10000 -->
<script>
  var iframe = document.createElement('iframe');
  iframe.style.display = 'none'; // 隐藏

  var state = 0; // 防止页面无限刷新
  iframe.onload = function() {
    
    
      if(state === 1) {
    
    
          console.log(JSON.parse(iframe.contentWindow.name));
          // 清除创建的iframe
          iframe.contentWindow.document.write('');
          iframe.contentWindow.close();
          document.body.removeChild(iframe);
      } else if(state === 0) {
    
    
          state = 1;
          // 加载完成,指向当前域,防止错误(proxy.html为空白页面)
          // Blocked a frame with origin "http://localhost:10000" from accessing a cross-origin frame.
          iframe.contentWindow.location = 'http://localhost:10000/proxy.html';
      }
  };

  iframe.src = 'http://localhost:10001';
  document.body.appendChild(iframe);
</script>

<!-- localhost:10001 -->
<!DOCTYPE html>
...
<script>
  window.name = JSON.stringify({
    
    a: 1, b: 2});
</script>
</html>

123456789101112131415161718192021222324252627282930313233343536373839

Method five: window.postMessage()

HTML5 new features can be used to send messages to all other window objects. It should be noted that we must ensure that all scripts are executed before sending MessageEvent. If it is called during the execution of the function, it will cause the subsequent function to time out and fail to execute.

The following code implements cross-domain storage localStorage

<!-- 
 下述用端口 
 10000表示:domainA
 10001表示:domainB
-->

<!-- localhost:10000 -->
<iframe src="http://localhost:10001/msg.html" name="myPostMessage" style="display:none;">
</iframe>

<script>
  function main() {
    
    
      LSsetItem('test', 'Test: ' + new Date());
      LSgetItem('test', function(value) {
    
    
          console.log('value: ' + value);
      });
      LSremoveItem('test');
  }

  var callbacks = {
    
    };
  window.addEventListener('message', function(event) {
    
    
      if (event.source === frames['myPostMessage']) {
    
    
          console.log(event)
          var data = /^#localStorage#(\d+)(null)?#([\S\s]*)/.exec(event.data);
          if (data) {
    
    
              if (callbacks[data[1]]) {
    
    
                  callbacks[data[1]](data[2] === 'null' ? null : data[3]);
              }
              delete callbacks[data[1]];
          }
      }
  }, false);

  var domain = '*';
  // 增加
  function LSsetItem(key, value) {
    
    
      var obj = {
    
    
          setItem: key,
          value: value
      };
      frames['myPostMessage'].postMessage(JSON.stringify(obj), domain);
  }
  // 获取
  function LSgetItem(key, callback) {
    
    
      var identifier = new Date().getTime();
      var obj = {
    
    
          identifier: identifier,
          getItem: key
      };
      callbacks[identifier] = callback;
      frames['myPostMessage'].postMessage(JSON.stringify(obj), domain);
  }
  // 删除
  function LSremoveItem(key) {
    
    
      var obj = {
    
    
          removeItem: key
      };
      frames['myPostMessage'].postMessage(JSON.stringify(obj), domain);
  }
</script>

<!-- localhost:10001 -->
<script>
  window.addEventListener('message', function(event) {
    
    
    console.log('Receiver debugging', event);
    if (event.origin == 'http://localhost:10000') {
    
    
      var data = JSON.parse(event.data);
      if ('setItem' in data) {
    
    
        localStorage.setItem(data.setItem, data.value);
      } else if ('getItem' in data) {
    
    
        var gotItem = localStorage.getItem(data.getItem);
        event.source.postMessage(
          '#localStorage#' + data.identifier +
          (gotItem === null ? 'null#' : '#' + gotItem),
          event.origin
        );
      } else if ('removeItem' in data) {
    
    
        localStorage.removeItem(data.removeItem);
      }
    }
  }, false);
</script>

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283

Pay attention to Safari, it will report an error:

Blocked a frame with origin “http://localhost:10001” from 
accessing a frame with origin “http://localhost:10000. 
Protocols, domains, and ports must match.

1234

To avoid this error, you can check the development menu==>disable cross-domain restriction in the Safari browser. Or it can only be implemented by server-side dumping, because the Safari browser only supports CORS cross-domain requests by default.

Method 6: Modify document.domain across subdomains

Prerequisite: The two domain names must belong to the same basic domain name! And the protocols and ports used must be the same, otherwise document.domain cannot be used for cross-domain, so only cross-subdomains

Within the scope of the root domain, it is allowed to set the value of the domain attribute to its parent domain. For example, in the " aaa.xxx.com " domain, you can set the domain to " xxx.com " but not " xxx.org " or "com".

现在存在两个域名aaa.xxx.com和bbb.xxx.com。在aaa下嵌入bbb的页面,
由于其document.name不一致,无法在aaa下操作bbb的js。
可以在aaa和bbb下通过js将document.name = 'xxx.com';
设置一致,来达到互相访问的作用。

12345

Method seven: WebSocket

WebSocket protocol is a new protocol for HTML5. It implements full-duplex communication between the browser and the server while allowing cross-domain communication. It is a great implementation of server push technology. For related articles, please check: WebSocket, WebSocket-SockJS

Note: The WebSocket object does not support DOM Level 2 event listeners, and each event must be defined separately using DOM Level 0 syntax.

Method eight: agency

The same-origin policy is a restriction on the browser side, which can be solved by the server side

DomainA client (browser) ==> DomainA server ==> DomainB server ==> DomainA client (browser)

Insert picture description here

87. Tell me about the implementation principle of JSONP?

jsonp is json+padding, dynamically creating script tags, and using the src attribute of script tags to get js scripts under any domain, through this feature (it can also be said that loopholes), the server side does not return the goods in json format, but returns a paragraph to call a certain The js code of each function is called in src, which realizes cross-domain.

Guess you like

Origin blog.csdn.net/xghchina/article/details/114902772