❤ A chat room case shows you how the Node.js+ws module realizes websocket communication!

Keywords: Javascript node.js websocket

Article catalog

🔥 1. Foreword  

🔥 2. Project structure analysis

🔥 3. Operation steps

🔥 4. View effect  

🔥 5. Previous good articles recommended

🔥 1. Foreword  

Hello, I'm a paper plane. If every day is endless knowledge, such learning must be very boring. Today, I'll bring you something with a sense of achievement: Node.js+ws module to make a simple chat room! There is a code address at the end of the text.

design sketch

After seeing the effect, are you curious about the implementation method? Next, I'll explain to you one by one:

🔥 2. Project structure analysis

Project catalog disassembly:

  1. Client folder: client configuration
  2. server.js: static server for client
  3. WebSocketServer.js: server configuration file

With the overall structure, next, hey hey.

🔥 3. Operation steps

get ready:

package.json can be obtained by executing the following commands:

npm init -y

Two dependent packages are required:

npm install ws --save-dev
npm install express --save-dev

Step 1: build the server (WebSocketServer.js)

const webSocket = require("ws"); //Introducing ws server module

const ws = new webSocket.Server({ port: 8000 }); //Create a server with port 8000
let clients = {};
let clientNum = 0;
ws.on("connection", (client) => {
  //Connect client

  //Number the client, that is, the users participating in the chat
  client.name = ++clientNum;
  clients[client.name] = client;

  // Chat information of users
  client.on("message", (msg) => {
    console.log("user" + client.name + "say:" + msg);
    //Broadcast data transmission and output
    broadcast(client, msg);
  //Error message
  client.on("error", (err) => {
    if (err) {
  // Offline
  client.on("close", () => {
    delete clients[client.name];
    console.log("user" + client.name + "Offline~~");

//Broadcasting method
function broadcast(client, msg) {
  for (var key in clients) {
    clients[key].send("user" + client.name + "Say:" + msg);

Step 2: client static server construction (server.js)

const express = require("express"); //Introducing express module
const path = require("path"); //Introducing disk path module
const app = express();
const port = 3000; //port
const host = ""; //host
app.use(express.static(path.resolve(__dirname, "./client"))); //Set the path to open the service

app.listen(port, host, () => {
  //Listener Service 
  console.log(`Client server is:http://${host}:${port}`);

Step 3: client page construction (index.html)

<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <h1>chat room</h1>
    <div id="content" name="name" style="overflow-y: scroll; width: 400px; height: 300px; border: solid 1px #000"></div>
    <br />
        <input type="text" id="msg" style="width: 200px;">
    <button id="submit">Submit</button>
    <script src="WSClient.js" charset="utf-8"></script>
        document.querySelector('#submit').addEventListener('click', function () {
            var msg2 = msg.value
            msg.value = ''
        }, false)


Step 4: connect the client to the server configuration (WSClient.js)

const ws = new WebSocket("ws:// "); / / connect to the client

//go online
ws.onopen = () => {
  ws.send("I'm online");
//Send message
ws.onmessage = (msg) => {
  const content = document.getElementById("content");
  content.innerHTML += msg.data + "<br>";
//report errors
ws.onerror = (err) => {

ws.onclose = () => {

It's done here.

Step 5: start websocketserver.js and server.js respectively

node WebSocketServer.js

node server.js

The above means that the startup is successful. Next, let's test locally. Students who want to play online can also upload and play by themselves.

🔥 4. View effect  

Open localhost:3000 with two browsers to view the effect:

Code download address: https://codechina.csdn.net/qq_32442973/websocket.git 

Little question: what should I do when websocket is disconnected (heartbeat)? (an article will be published later)

🔥 5. Previous good articles recommended

Posted by craigw9292 on Mon, 13 Sep 2021 22:34:49 -0700