Express+websocket realizes online chat

1. Introduction to webSocket

WebSocket is a communication protocol that enables full-duplex communication over a single TCP connection. WebSocket makes the data exchange between the client and the server easier, allowing the server to actively push data to the client. In the WebSocket API, the browser and the server only need to complete a handshake, and a persistent connection can be established between the two for two-way data transmission

  • WebSocket is a new protocol under HTML5 (the websocket protocol is essentially a tcp-based protocol)
  • Websocket is a persistent protocol

2. The principle of websocket 

  1. Websocket stipulates a communication specification. Through a handshake mechanism, a TCP-like connection can be established between the client and the server, thereby facilitating the communication between them.
  2. Before the emergence of websockets, web interactions were generally short or long connections based on the http protocol
  3. websocket is a brand new protocol, not part of http stateless protocol, the protocol name is "ws"

3. What is the difference between websocket and http?

Same point:

  1. Both are based on tcp, and they are all reliable transmission protocols.
  2. are application layer protocols

difference:

  1. WebSocket is a two-way communication protocol, simulating the Socket protocol, which can send or receive information in both directions
  2. HTTP is one-way
  3. WebSocket requires a handshake between the browser and the server to establish a connection
  4. And http is a connection initiated by the browser to the server, and the server does not know this connection in advance.

a link between

When WebSocket establishes the handshake, the data is transmitted through HTTP. But after the establishment, the HTTP protocol is not required for real transmission

4. Websocket improvements

Once the WebSocket connection is established, subsequent data is transmitted in the form of a sequence of frames. Before the client disconnects the WebSocket connection or the server disconnects, the client and the server do not need to re-initiate the connection request. In the case of massive concurrency and heavy traffic between the client and the server, it greatly saves the consumption of network bandwidth resources and has obvious performance advantages, and the client sends and receives messages on the same persistent connection. With the "true long link", the real-time advantage is obvious

 

5. Problems solved by websocket

1. Problems with http

  • HTTP is a stateless protocol. Every time a session is completed, the server does not know who the next client is. It needs to know who the other party is before responding accordingly. Therefore, it is a kind of real-time communication itself. great obstacle
  • The http protocol uses one request and one response. Each request and response carries a large number of headers. For real-time communication, parsing the request header also takes a certain amount of time, so the efficiency is also lower.
  • The most important thing is that the client needs to take the initiative to send, and the server to send passively, that is, one request and one response, and active sending cannot be realized

2.long poll (long poll)

  • For the above situation, there is the first method of http solution - long polling
  • Based on the characteristics of http, to put it simply, the client initiates long polling. If the data on the server does not change, it will hold the request until the data on the server changes or wait for a certain period of time before returning. After returning, the client will immediately initiate the next long poll again
  • The advantage is that it solves the disadvantage that http cannot update in real time, because this time is very short, the request is processed and the response is returned after the request is initiated, and the "pseudo-long connection" is realized

3. Ajax polling

  • Based on the characteristics of http, to put it simply, it is stipulated that the client initiates a request every once in a while to check whether there is any new news. If there is, it will return. If it does not wait for the same time interval, it will ask again
  • The advantage is that it solves the disadvantage that http cannot be updated in real time, because this time is very short, when the request is initiated, the request is processed and the response is returned, and the process is enlarged by n times, essentially request = response

  code display

 download

npm i express-ws

app.js

var ws = require('express-ws')


var app = express();
ws(app)


app.listen('8888')

index.js

var express = require('express');
var router = express.Router();
var ws = require('express-ws')
ws(router)
const wss = []
router.ws("/",(ws,req)=>{
  // console.log("连接成功!");
  // send给客户端发消息
  // on是监听事件
  // message表示服务端传来的数据
  wss.push(ws)
  ws.on("message", (msg) => {
    console.log(msg);
      // 给所有的客户端广播消息
      // console.log(msg);
      // console.log(wss);
      wss.forEach((e) => {
          e.send(msg)
      })
  })
  // close 事件表示客户端断开连接时执行的回调函数
ws.on('close', function (e) {
  console.log('close connection')
})

})
module.exports = router;

html page (root directory creation)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text" name="msg" id="msg">
    <input type="button" value="发送" id="btn">
    <ul id="showMsg"></ul>
    <script>
        function UrlSearch() {
            var name, value;
            var str = location.href; //取得整个地址栏
            var num = str.indexOf("?")
            str = str.substr(num + 1); //取得所有参数 stringvar.substr(start [,length ]
            var arr = str.split("&"); //各个参数放到数组里
            for (var i = 0; i < arr.length; i++) {
                num = arr[i].indexOf("=");
                if (num > 0) {
                    name = arr[i].substring(0, num);
                    value = arr[i].substr(num + 1);
                    this[name] = value;
                }
            }
        }
        var Request = new UrlSearch(); //实例化
        var ws = new WebSocket("ws://localhost:8888");
        var btn = document.getElementById('btn')
        var inputDom = document.getElementById('msg')
        var ulDom = document.getElementById('showMsg')
        btn.addEventListener('click', function () {
            ws.send(inputDom.value)
            inputDom.value = ''
        })
        ws.onopen = function (evt) {
            console.log("Connection open ...");
            //ws.send("Hello WebSockets!");
        };
        let liHtml = ''
        ws.onmessage = function (evt) {
            console.log(evt.data);
            liHtml += `<li>:${evt.data}</li>`
            ulDom.innerHTML = liHtml
        };
        ws.onclose = function (evt) {
            console.log("Connection closed.");
        };
    </script>
</body>
</html>

Open two html pages at the same time in the browser

another page

backend printing

Such a simple online chat is completed, this is multi-chat, and single-chat mode can also be realized 

Guess you like

Origin blog.csdn.net/qq_60976312/article/details/129383642