[websocket] front-end websocket real-time communication

Front-end websocket real-time communication

what is websocket

Websocket is a network communication protocol provided by HTML5. The purpose of its birth is to establish an unlimited two-way communication channel between browsers. For example, the server can send information to the browser at any time. In the websocket API, the browser and the server only need to complete a handshake, and a persistent connection can be created directly between the two, and two-way data transmission can be performed.

Why the traditional http protocol can't achieve the function of websocket

The http protocol is a request-response protocol, the request must be sent to the server by the browser before the server can respond

Comparison of events used by the front and back ends of websocket

insert image description here

WebSocket.readyState

  • The readyState property returns the current state of the instance object, and there are four states in total
  • 0 - means connecting
  • 1 - Indicates a successful connection and communication is possible
  • 2 - means the connection is closing
  • 3 - indicates that the connection has been closed, or failed to open the connection

the code

Install the ws package

npm i ws -d

A successful websocket connection will generate a key, which is used to identify the connection, not encrypted

index.htm

<!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>
    <h3>我是客户端</h3>


    <script>
      let ws = new WebSocket('ws://localhost:5000') //接口地址
      //连接成功后
      ws.onopen = (evt) => {
    
    
        console.log('连接开启')
        ws.send('hello 我是客户端') //利用send向后端发送数据
      }

      //传递和接收服务器数据的方法
      ws.onmessage = (evt) => {
    
    
        console.log('我是服务器传递过来的消息---' + evt.data)
        ws.send('我是客户端发送的第二条信息')
        ws.close()
      }

      // 连接失败时触发
      ws.onerror = () => {
    
    
        alert('连接失败')
      }

      // 连接关闭
      ws.onclose = () => {
    
    
        alert('连接关闭')
      }
    </script>
  </body>
</html>

index.js

const Websocket = require("ws")
//引用server类并且实例化,定义服务器端口为3306
const wss = new Websocket.Server({
    
     port: 5000 })

wss.on("connection", (ws) => {
    
    
    ws.on("message", (message) => {
    
    
        console.log(`客户端发送过来的信息是${
      
      message}`);
        ws.send("我是服务器")
    })
})

Guess you like

Origin blog.csdn.net/m0_63779088/article/details/128615527