“This is the 15th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

In this article, I will start with a brief introduction to WebSocket; Then use Node + WebSocket to make a very rudimentary chat room; Finally, this simple chat room through the Websocket framework – socket. IO for production.

1. Get to know Websocket

① What is websocket

HTML5 began to provide a browser and server for full duplex communication network technology, belongs to the application layer protocol. It is based on the TCP transport protocol and reuses the HTTP handshake channel. Websocket is a natural full-duplex, bidirectional, single-socket connection. The HTTP protocol is not suitable for real-time communication. It was proposed in 2008 and became an international standard in 2011. The Websocket protocol enables full-duplex communication between the client and server through the Web, and supports transmission of binary data and text strings. The protocol consists of an initial handshake and a basic messaging framework that is built on top of TCP. Compared with HTTP protocol, Websocket link can carry out bidirectional real-time communication once established.

The following diagram is a flow chart of HTTP connection and WebSocket connection

(2) the characteristics of

  1. Based on TCP protocol, the implementation of the server side is relatively easy.
  2. It has good compatibility with HTTP protocol. The default ports are also 80 and 443, and the handshake phase uses HTTP protocol, so it is not easy to mask the handshake and can pass various HTTP proxy servers.
  3. The data format is relatively light, with low performance overhead and high communication efficiency.
  4. You can send text or binary data.
  5. There are no same-origin restrictions, and clients can communicate with any server.

③ Complementary technology

Server – sent Events (SSE) : www.ruanyifeng.com/blog/2017/0… www.cnblogs.com/goloving/p/…

SPDY (pronounced “SPeeDY”) : no longer maintenance, replaced by HTTP / 2 baike.baidu.com/item/SPDY/3…

WebRTC baike.baidu.com/item/WebRTC…

WebRTC is estimated to be familiar to many people. Websocket is generally suitable for real-time text communication, while audio and video communication is generally using WebRTC technology

2. Get started

① Use browser + Websocket + Node to create a simple chat room

In fact, websocket technology still has a lot of theoretical knowledge, because it is more partial to the network, will be more boring, interested can go to search the relevant knowledge. Now I’m going to take you straight into the field.

Ⅰ. The service side

  1. Step 1: Create an empty folder and initialize the entire folder with NPM init -y

  2. Install the websocket: NPM install websocket, websocket NPM package website: www.npmjs.com/package/web…

  3. Create a file in the directory named server.js

  4. First, we need to introduce websockets, and it’s important to introduce HTTP modules, because Websockets are based on the HTTP protocol

    const  websocket = require('websocket').server
    
    const http = require('http')
    Copy the code
  5. Then start HTTP, start the server, and listen

    const httpServer = http.createServer().listen(8080.() = >{
            console.log('nihao: '.'http://localhost:8080');
    })
    Copy the code
  6. Create a WebSocket service with two mandatory parameters

    const websocketServer = new websocket({
            httpServer: httpServer,
            autoAcceptConnections: false
    })
    Copy the code
  7. Create a communication line pool, if you do not use a database, you need to use an array to make a virtual line pool, because websocket is a real-time communication, the communication between the server and the client is back and forth, need to store these communication data. Redis is generally used for line pooling, and then the maximum amount of data stored is generally 1000

    const conArr = []
    Copy the code
  8. Use webSocket to accept requests and send messages, using the.on(‘requset’, function(){}) and.on(‘message’, function(){} methods in the NPM package of the webSocket. The use of these methods can be viewed from the NPM documentation of websocket or from Github

    websocketServer.on('request'.function(request) {
    	// This is a message sent by the client
    	// Websocket needs to save the link
    	// As long as the client and server are not disconnected, this link must be in
     	// The client communicates with the server from this link
    	const connection = request.accept()
    
    	// Take one link at a time and store it in the array
    	conArr.push(connection)
    
    	// Listen for messages sent by the client
    	connection.on('message'.function(message) {
        	console.log(message);
     		// Send messages to clients (broadcast to individual clients)
      		// Add utf8Data encoding
     		// Each client receives incoming data only after all links are sent
      		for(let i = 0; i < conArr.length; i++) {
       			conArr[i].send(message.utf8Data)
       		}
    	})
    })
    Copy the code
  9. Finally, start the server:node server.js

Ⅱ. The client

  1. To create an index. HTML file in a folder, start by writing a simple HTML page

    <! Create a link as soon as you enter the browser --> <! -- Click the button to send a message to the server --> Enter the name: <input type="text" id="uName"> <br> Input message: <input type="text" id="context">
    
    <button id="btn">Click Send message</button>
    
    <div id="charRoom"></div>
    Copy the code
  2. First through JS to get the nodes in the page, all the time through these nodes for a series of operations

    / / user name
    const uName = document.getElementById('uName')
    // Text box content
    const context = document.getElementById('context')
    // Click the button
    const btn = document.getElementById('btn')
    // The area to display the chat room
    const charRoom = document.getElementById('charRoom')
    Copy the code
  3. Note that since webSocket comes with the browser, you can simply instantiate the WebSocket object through New without downloading or importing anything. Websocket’s own methods are used in the browser: websocket.onopen. The various methods of websocket can be viewed in the MDN documentation: developer.mozilla.org/zh-CN/docs/…

    // instantiate webSocket
    //localhost:8080' ws://localhost:8080
    const websocket = new WebSocket('ws://localhost:8080')
    // Open the event
    websocket.onopen = function() {
      // Get the status of the current link
      // 1 establishes the link
      console.log(websocket.readyState);
    }
    Copy the code
  4. Create a button click event that sends data to the server through webSocket. The message is sent through webSocket’s websocket. onMessage method, which takes one parameter, The parameter is the data that you want to send. Note, however, that since none of the data you retrieve from the page is in JSON object format, you need to convert the data to JSON object format before sending it.

    // Click the event that sends the message
    btn.onclick = function() {
      // Put the user name and the content to be sent in an object and pass it to the back end
      const values = {
        uName: uName.value,
        context: context.value
      }
    
      // Clear the contents of the text box
      uName.value = ' '
      context.value = ' '
    
      // Send messages via websockte
      websocket.send(JSON.stringify(values))
    }
    Copy the code
  5. Finally, let the browser listen to the message delivered by the server in real time, need to get the message sent by the server through websocket websocket. onMessage method. Here I concatenate the text content in the form of template strings.

    // Receive the message returned by the server
    websocket.onmessage = function(data) {
      // The chat message returned by the server
      const chatS = JSON.parse(data.data)
    
      // Add to the page
      charRoom.innerHTML += `
        <strong>${chatS.uName}: < / strong > < span >${chatS.context}</span>
        <br />
      `
    }
    Copy the code

ⅲ. Effect viewing

At this time open the browser, you can achieve real-time communication between clients. Because you want to see real-time communication between clients, you can open multiple browsers to see the effect:That’s it for a simple chat room using native WebSocket + Node.

ⅳ. Complete code

Server.js complete code for the server

const  websocket = require('websocket').server

const http = require('http')

const httpServer = http.createServer().listen(8080.() = >{
  console.log('nihao: '.'http://localhost:8080');
})

// Create webSocket server
const websocketServer = new websocket({
  httpServer: httpServer,
  autoAcceptConnections: false
})

Redis usually a link pool with a maximum of 1000
// Store links
// But there is a maximum upper limit
const conArr = []

websocketServer.on('request'.function(request) {
  // This is a message sent by the client
  // Websocket needs to save the link
  // As long as the client and server are not disconnected, this link must be in
  // The client communicates with the server from this link
  const connection = request.accept()

  // Take one link at a time and store it in the array
  conArr.push(connection)

  // Listen for messages sent by the client
  connection.on('message'.function(message) {
    console.log(message);
    // Send messages to clients (broadcast to individual clients)
    // Add utf8Data encoding
    // Each client receives incoming data only after all links are sent
    for(let i = 0; i < conArr.length; i++) {
      conArr[i].send(message.utf8Data)
    }
  })

  // The server fires when the client disconnects
  // connection.on('close')
})
Copy the code

Index. HTML client complete code

<! DOCTYPEhtml>
<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>
  <! Create a link as soon as you enter the browser -->
  <! -- Click the button to send a message to the server -->Enter your name:<input type="text" id="uName">
  <br>Input message:<input type="text" id="context">

  <button id="btn">Click Send message</button>

  <div id="charRoom"></div>

  <script>
    / / user name
    const uName = document.getElementById('uName')
    // Text box content
    const context = document.getElementById('context')
    // Click the button
    const btn = document.getElementById('btn')
    // The area to display the chat room
    const charRoom = document.getElementById('charRoom')
    
    // instantiate webSocket
    //localhost:8080' ws://localhost:8080
    const websocket = new WebSocket('ws://localhost:8080')
    // Open the event
    websocket.onopen = function() {
      // Get the status of the current link
      // 1 establishes the link
      console.log(websocket.readyState);
    }

    // Click the event that sends the message
    btn.onclick = function() {
      // Put the user name and the content to be sent in an object and pass it to the back end
      const values = {
        uName: uName.value,
        context: context.value
      }

      // Clear the contents of the text box
      uName.value = ' '
      context.value = ' '

      // Send messages via websockte
      websocket.send(JSON.stringify(values))
    }

    // Receive the message returned by the server
    websocket.onmessage = function(data) {
      // The chat message returned by the server
      const chatS = JSON.parse(data.data)

      // Add to the page
      charRoom.innerHTML += `
        <strong>${chatS.uName}: < / strong > < span >${chatS.context}</span>
        <br />
      `
    }

    // When the server is disconnected, the client triggers
    // websocket.onclose = function() {}
  </script>
</body>
</html>
Copy the code

② Create a chat box using socket. IO

Socket. IO to webSocket to do a very complete package, the core code only need a few steps can be completed, specific steps I will not be introduced to the above so detailed, here I directly give you the complete code, can be combined with my annotations to eat. IO /docs/v4/

Server.js complete code for the server

/ / socket. IO framework
// Introduce the createServer method of the HTTP module
const { createServer } = require('http')

// Import the Server module of socket. IO
const { Server } = require('socket.io')

// instantiate httpServer
const httpServer = createServer();

// Initialize socket. IO
const io = new Server(httpServer, {
  cors: {
    origin: The '*'.methods: ['GET'.'POST']}})// Use socket. IO to establish a connection
io.on('connection'.socket= > {
  socket.on('sendMsg'.data= > {
    io.emit('pushMsg', data)
    console.log(data); })})// Create a server to listen on
httpServer.listen(8080.function() {
  console.log('http://localhost:8080');
})
Copy the code

Note the complete code for the client side here, because in order to use the scoke. IO framework, it must be introduced first. There are various import methods on the official website, such as CDN import or download directly to the local for import.

<! DOCTYPEhtml>
<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>
  <script src="https://cdn.socket.io/4.4.0/socket.io.min.js"
    integrity="sha384-1fOn6VtTq3PWwfsOrk45LnYcGosJwzMHv+Xh/Jx5303FVOXzEnw0EpLv30mtjmlj" crossorigin="anonymous">
  </script>
</head>
<body>
  <! Create a link as soon as you enter the browser -->
  <! -- Click the button to send a message to the server -->Enter your name:<input type="text" id="uName">
  <br>Input message:<input type="text" id="context">

  <button id="btn">Click Send message</button>

  <div id="charRoom"></div>

  <script>
    / / user name
    const uName = document.getElementById('uName')
    // Text box content
    const context = document.getElementById('context')
    // Click the button
    const btn = document.getElementById('btn')
    // The area to display the chat room
    const charRoom = document.getElementById('charRoom')

    // Use socket. IO to connect to the server
    const socket = io.connect('http://localhost:8080')

    // Click the event that sends the message
    btn.onclick = function() {
      // Put the user name and the content to be sent in an object and pass it to the back end
      const values = {
        uName: uName.value,
        context: context.value
      }

      // Clear the contents of the text box
      uName.value = ' '
      context.value = ' '

      // Send data to the server through socket. IO
      socket.emit('sendMsg', values)
    }
    
    // Use the socket.on method to listen for data sent from the server
    socket.on('pushMsg'.data= > {
      // Add to the page
      charRoom.innerHTML += `
        <strong>${data.uName}: < / strong > < span >${data.context}</span>
        <br />
      `
    })
  </script>
</body>
</html>
Copy the code

Here’s an example: