Basic use of WebSocket - implement a simple multi-person chat room

renderings

The main function of webSocket is to achieve real-time two -way communication . The main difference from http communication is that the server can actively send messages to the front end in websocket, while in http it can only passively receive and respond to requests.

As shown in the figure below, there are four clients in total, one person sends a message, and all of them will receive the message instantly.

insert image description here

The use of front-end WebSocket

In fact, the front-end websocket is very simple to use. Looking at the official documentation , you can find that the properties, methods, and events of the websocket object are few, so it is very easy to get started. Let me briefly explain that to use WebSocket, there are actually three steps to do:

  • Call the WebSocket constructor to generate a websocket object
  • Add event listener for WebSocket
  • Call the send method of the object to send the message

The front-end code is as follows:

<!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>
  <div class="container">
    <div class="chat-box">
      <h3>聊天内容</h3>
    </div>
    <textarea class="message"></textarea>
    <button class="send">发送</button>
  </div>
  <script>
    const chatBox = document.querySelector('.chat-box')
    const textarea = document.querySelector('.message')
    const sendButton = document.querySelector('.send')
    // 生成WebSocket对象
    const ws = new WebSocket('ws://localhost:9002/ws')

    // 为WebSocket添加事件监听
    ws.addEventListener('message', function (event) {
      
      
      const li = document.createElement('li')
      li.innerText = event.data
      chatBox.append(li)
    });
    ws.addEventListener('open', () => {
      
      
      console.log('websocket连接建立完毕')
    })

    sendButton.addEventListener('click', () => {
      
      
      // 发送消息
      ws.send(textarea.value)
    })
  </script>
  <style>
    .container{
      
      
      width: 300px;
      height: 300px;
      display: flex;
      flex-wrap: wrap;
      align-content: space-between;
      border: 2px rgb(10, 193, 89) dashed;
      padding: 5px;
    }
    .chat-box{
      
      
      padding: 0 10px;
      overflow: auto;
      height: 60%;
      width: 100%;
      border: rgb(205, 37, 37) solid 2px;
    }
    .chat-box > h3{
      
      
      margin: 0;
      text-align: center;
      overflow: auto;
    }
    .message{
      
      
      width: 100%;
      height: 15%;
    }
    .send{
      
      
      height: 15%;
      width: 100%;
      font-size: larger;
    }
  </style>
</body>

</html>

Backend WebSocket server

Implementing a WebSocket server at the back end is much more difficult than the front-end steps above, because the need for multi-person instant chat will inevitably involve multi-thread and inter-thread communication, and also consider the failure, error, and issues such as recycling. I originally wanted to learn and use golang to write this websocket server, but after reading the document for two hours, I didn’t understand it at all, sweat (lll¬ω¬). Alas, I still have too little knowledge on the back end, and my skills are not enough. I can't understand many io operations and thread operations.

Here, I use nodejs to implement a simple WebSocket server, specifically using the ws library, the code is as follows:

// 导入WebSocket模块:
const WebSocket = require('ws');

// 引用Server类:
const WebSocketServer = WebSocket.Server;

// 实例化:
const wss = new WebSocketServer({
    
    
    port: 9002,
    path: '/ws'
});

let wsList = []

// 监听创建连接事件,回调函数的参数是创建的连接
wss.on('connection', function connection(ws) {
    
    
  ws.on('error', console.error)

  // 监听该连接的接收信息事件
  ws.on('message', function message(data) {
    
    
    console.log('接收到信息: %s', data)
    for(let w of wsList){
    
    
      if(w.readyState == w.OPEN){
    
    
        w.send(data.toString())
      }
    }
  })

  wsList.push(ws)
})

Guess you like

Origin blog.csdn.net/m0_52744273/article/details/129690901