The business scenarios and requirements of instant messaging are a hodgepodge of short connections, long connections, and Socket introductions

Business scenarios and requirements of instant messaging

Instant Messaging (IM) is a method that allows two or more people to use the network to communicate text messages, files, voice, and video in real time. Instant messaging technology is applied to business scenarios that need to send and receive messages in real time .
Now all kinds of instant messaging software are also emerging in endlessly:

Insert picture description here

  • Social APPInsert picture description here

  • Smart hardware, Internet of Things

Insert picture description here

2 Short connection and long connection

Instant messaging uses long connections. Here we introduce short and long connections.

2.1 Short connection

Each time the client and server communicate, a connection is established, and the connection is terminated when the communication ends.
Insert picture description here

HTTP is a simple request-response protocol, it usually runs on top of TCP. The TCP used by HTTP/1.0 is a short connection by default.

2.2 Long connection

It means that after the connection is established, data can be sent multiple times in a row until the two parties disconnect.
Insert picture description here

Starting from version 1.1 of HTTP, the underlying TCP uses a long connection.
Use the HTTP protocol of long connection, will add the code in the response header:Connection:keep-alive

2.3 The difference between short connection and long connection

2.3.1 Communication process

Short connection: Create connection -> Transfer data -> Close connection Long connection: Create connection -> Transfer data -> Keep connection -> Transfer data -> …… -> Close connection

2.3.2 Applicable scenarios

Short connection: large amount of concurrency, infrequent data interaction
Long connection: frequent data interaction, point-to-point communication

2.3.3 Communication method

the way Description
Short connection I am sending a message to you. I must wait until you reply to me or if I can’t wait for a while, I will end the communication.
Long connection I send messages to you and keep in communication. During this period of communication, you reply to me while I am doing other things. I can reply to me immediately, and then I can respond or not, and continue to do things.

3 websocket protocol

1. What is WebSocket?

  • WebSocket is a protocol that HTML5 began to provide for full-duplex communication on a single TCP connection.

    • What is full duplex: Full duplex (Full Duplex) is a term for communication transmission. The two parties allow data to be transmitted in both directions at the same time during communication, which is equivalent to a combination of two simplex communication methods in terms of capability. Full duplex refers to the two-way transmission of signals at the same time. Refers to A→B and B→A at the same time, which is like a two-way lane.
    • Simplex is like a one-way street for cars, in that it only allows Party A to transmit information to Party B, and Party B cannot transmit to Party A.
  • Reference material: https://baike.baidu.com/item/%E5%85%A8%E5%8F%8C%E5%B7%A5/310007?fr=aladdin

  • In WebSocket, the browser and the server only need to complete a handshake to create a persistent connection and perform two-way data transmission.

  • In the implementation technology of the push function, WebSocket saves server resources and bandwidth more than using Ajax timing polling (setInterval).

  • The function of the server to send data to the client is a typical usage scenario of the websocket protocol
    Insert picture description here

2. Why do we need WebSocket?

We know that the traditional HTTP protocol is stateless. Each request (request) must be initiated by the client (such as a browser). The server returns the response result after processing, but it is difficult for the server to actively send to the client. Data; this kind of traditional Web mode, where the client is the active side and the server is the passive side, causes less trouble for Web applications with infrequent information changes, but brings great problems for Web applications involving real-time information. inconvenient.

Therefore, with the birth of HTML5, a new communication protocol came into being—WebSocket. Its biggest feature is that the server can actively push messages to the client, and the client can also actively send messages to the server, realizing the real equality.

** For example: ** Such as applications with instant messaging, real-time data, subscription push and other functions. Before the WebSocket specification was proposed, if developers wanted to implement these real-time functions, they often used a compromise solution: ajax polling (the most primitive solution for real-time web applications)

**The principle of ajax polling: **The principle of ajax polling is very simple. Let the browser send a request every few seconds to ask the server if there is new information. Obviously, this method will cause too many unnecessary requests, wasting traffic and server resources.

Scene reproduction:

客户端:有没有新信息(Request)
服务端:没有(Response)
客户端:有没有新信息(Request)
服务端:没有。。(Response)
客户端:有没有新信息(Request)
服务端:你好烦啊,没有啊。。(Response)
客户端:有没有新消息(Request)
服务端:有啦,给你。(Response)
客户端:有没有新消息(Request)
服务端:。。。。。没。。。。没。。。没有(Response) ---- loop

The principle of websocket: When the server completes the protocol upgrade (HTTP->Websocket), the server can actively push information to the client.

Scene reproduction:

客户端:我要建立Websocket协议,需要的服务:chat,Websocket协议版本:17(HTTP Request)
服务端:确认,已升级为Websocket协议(HTTP Protocols Switched)
客户端:麻烦你有信息的时候推送给我噢。。
服务端:好的,有的时候会告诉你的。
服务端:balabalabalabala
服务端:哈哈哈哈哈啊哈哈哈哈
服务端:笑死我了哈哈哈哈哈哈哈

3. Other features of WebSocket are as follows:

(1) Based on the TCP protocol, the server-side implementation is relatively easy.

(2) It has good compatibility with HTTP protocol. The default ports are also 80 and 443, and the HTTP protocol is used in the handshake phase, so it is not easy to block during the handshake and can pass through various HTTP proxy servers.

(3) The data format is relatively lightweight, the performance overhead is small, and the communication is efficient.

(4) You can send text or binary data.

(5) There is no homology restriction, and the client can communicate with any server.

(6) The protocol identifier is ws (if encrypted, it is wss), and the server website is the URL.

Fourth, create a WebSocket object

The browser sends a request to establish a WebSocket connection to the server through JavaScript. After the connection is established, the client and server can directly exchange data through the TCP connection. After you get the WebSocket connection, you can send data to the server through the send() method, and receive the data returned by the server through the onmessage event.

// url, 指定连接的 URL
// protocol 是可选的,指定可接受的子协议。
let Socket = new WebSocket(url, [protocol] );

Five, WebSocket attributes

  假设我们创建了一个Socket对象

Property description
Socket.readyState
read-only property readyState indicates the connection state, which can be the following values:

0-Indicates that the connection has not been established yet.

1-Indicates that the connection has been established and communication is possible.

2-Indicates that the connection is being closed.

3-Indicates that the connection has been closed or the connection cannot be opened.

Socket.bufferedAmount read-only attribute bufferedAmount has been put into the queue waiting for transmission by send(), but the number of UTF-8 text bytes that have not been sent.

Six, WebSocket events

Suppose we create a Socket object

event Event handler description
open Socket.onopen Triggered when the connection is established
message Socket.onmessage Triggered when the client receives server data
error Socket.onerror Triggered when a communication error occurs
close Socket.onclose Triggered when the connection is closed

Seven, WebSocket method

Suppose we create a Socket object

method description
Socket.send() Use connection to send data
Socket.close() Close the connection

Eight, WebSocket instance

JavaScript

<!DOCTYPE html>
<html>
 
<head>
  <meta charset="utf-8">
</head>
<style>
</style>
 
<body>
  <input id="text" type="text" />
  <button onclick="send()">发送消息</button>
  <button onclick="closeWebSocket()">关闭WebSocket连接</button>
  <div id="message"></div>
 
  <script>
    let websocket = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
      websocket = new WebSocket("ws://localhost:8080/websocket");
    } else {
      alert('当前浏览器不支持websocket!')
    }
 
    //连接发生错误的回调方法
    websocket.onerror = function () {
      console.log("WebSocket连接发生错误");
    };
    //连接成功建立的回调方法
    websocket.onopen = function () {
      console.log("WebSocket连接成功");
    }
 
    //接收到消息的回调方法
    websocket.onmessage = function (event) {
      document.getElementById('message').innerHTML += event.data + '<br/>';
    }
 
    //连接关闭的回调方法
    websocket.onclose = function () {
      console.log("WebSocket连接关闭");
    }
 
    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function () {
      closeWebSocket();
    }
 
    //关闭WebSocket连接
    function closeWebSocket() {
      websocket.close();
    }
 
    //发送消息
    function send() {
      let message = document.getElementById('text').value;
      websocket.send(message);
    }
  </script>
</body>
 
</html>

View

<template>
  <div>
    <el-input v-model="params" clearable/>
    <el-button type="primary" @click="send">发消息</el-button>
  </div>
</template>
 
<script>
  export default {
    data() {
      return {
        params: '',
        path: "ws://localhost:8080/websocket",
        socket: ""
      }
    },
    mounted() {
      // 初始化
      this.init()
    },
    destroyed() {
      // 销毁监听
      this.socket.onclose = this.close
    },
    methods: {
      init: function () {
        if (typeof (WebSocket) === "undefined") {
          console.log("您的浏览器不支持socket")
        } else {
 
          // 实例化socket
          this.socket = new WebSocket(this.path)
 
          // 监听socket连接成功回调
          this.socket.onopen = this.open
          
          // 监听socket连接失败回调
          this.socket.onerror = this.error
 
          // 监听后台返回的socket消息
          this.socket.onmessage = this.getMessage
        }
      },
      open: function () {
        console.log("socket连接成功")
      },
      error: function () {
        console.log("连接错误")
      },
      getMessage: function (msg) {
        console.log(msg.data)
      },
      send: function () {
        this.socket.send(params)
      },
      close: function () {
        console.log("socket已经关闭")
      }
    }
  }
</script>

Guess you like

Origin blog.csdn.net/pjh88/article/details/115052171