[Byte Ali Tencent Interview Dry Goods] Three handshake, two times can't? The knowledge that you made mistakes accidentally is organized here!

2020 latest Java collection of common interview questions + detailed answers (7)

Recently, many people around me are asking me questions about interviews with big factories. Therefore, I am also combining the interview questions of myself and my friends to sort out common and basic Java interview questions. The first few collections have been posted on the homepage.

Some of the answers are summarized by myself, and some are collected on the Internet. Don't panic after watching these interviews! If you have more experience, you can share it in the comments. If you have any mistakes, you are welcome to point it out. Please let me know, thank you~

The internet

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

 

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

 

the difference: 

 

  • 301 redirect: 301 stands for Permanently Moved.

  • 302 redirect: 302 stands for Temporarily Moved. 

 

62. 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."


63. 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, there is no need to establish a connection before sending data.

  • TCP provides reliable services. In other words, 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.

  • Tcp 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-order 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.

 

64. Why does tcp need to shake hands 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.

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

 

  1. Application layer: an interface between network services and end users.

  2. Presentation layer: data presentation, security, and compression.

  3. Session layer: establish, manage, and terminate sessions.

  4. Transport layer: Define the protocol port number for data transmission, as well as flow control and error checking.

  5. Network layer: Perform logical address addressing to realize path selection between different networks.

  6. Data link layer: establish logical connection, perform hardware address addressing, error checking and other functions.

  7. Physical layer: establish, maintain, and disconnect physical connections.

 

66. 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 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 sent in the URL for GET requests are limited in length, but not for POST.

  • For the data type of the parameter, GET only accepts ASCII characters, while POST has no restrictions.

  • GET is less secure than POST, because the 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.

Let me see if you have a good memory

67. How to achieve cross-domain?

 

Method 1: Image ping or script tag cross-domain

 

Image ping is often used to track the number of times users click on a page or dynamic ad exposure. 
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 using this open policy of the <script> element, web pages can obtain JSON data dynamically generated from other sources, and this usage mode is the so-called JSONP. The data captured with JSONP is not JSON, but arbitrary JavaScript, run with a JavaScript interpreter instead of parsed with a JSON parser. All, through Chrome, all Get requests sent by JSONP are of js type, not XHR. 

 

Disadvantages:

 

  • Only use Get request

  • Cannot register event monitoring functions such as success and error, and cannot easily determine whether the JSONP request failed

  • JSONP is executed by loading code from other domains, and 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

 

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

 

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.

 

  • The cross-domain capability of iframe tags;

  • The ability of the window.name attribute value to still exist after the document is refreshed (and the maximum allowed 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 <iframe> 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>

 

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>

 

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.

 

 

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, the domain can be set to "xxx.com" but not "xxx.org" or "com".

There are now two domain names aaa.xxx.com and bbb.xxx.com. Pages embedded with bbb under aaa, because their document.names are inconsistent, the js of bbb cannot be operated under aaa. You can set document.name ='xxx.com'; consistent under aaa and bbb through js to achieve mutual access.

 

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: WebSocket objects do 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)

 

Source: blog.csdn.net/ligang2585116/article/details/73072868

 

68. 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 obtain js scripts in any domain, through this feature (or a vulnerability), the server does not return the goods in json format, but returns a paragraph to call a certain The js code of a function is called in src, which realizes cross-domain.

At last

The content of the interview questions is over here, I hope it will be helpful to everyone.

Finally, I want to say something to you. I have worked for so many years and have interviewed some people for others. Whether it is from the perspective of the interviewer or the leader, in addition to interview skills and experience, great technology and project experience are also their trump cards and confidence. Core technology sharing of first-tier manufacturers

 It took me a long time to sort out some learning materials. What I posted above is the tip of the iceberg in the materials. I hope I can help you! Click to learn together cipher: csdn

                         

  I will share more pure dry goods articles in the follow-up, and hope to really help you. Your support is my biggest motivation!

Guess you like

Origin blog.csdn.net/weixin_50333534/article/details/108805134