The article directories

🔥 1. Preface

🔥 2. Project structure analysis

🔥 3. Procedure

🔥 4. View the effect

🔥 5. Recommend good articles in the past


🔥 1. Preface

Hello, I’m paper airplane. If every day is endless knowledge, then such learning must be very boring. Today I will bring you a sense of achievement: Node.js+ WS module to create a simple chat room! There’s a code address at the end.

rendering

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

🔥 2. Project structure analysis

Project catalog disassembly:

  1. Client folder: client configuration
  2. Server.js: static server for the client
  3. Websocketserver. js: server configuration file

We have the overall structure, and then, hey, hey.

🔥 3. Procedure

Preparation:

Package. json is obtained by executing the following command:

npm init -y
Copy the code

Two dependency packages are required:

npm install ws --save-dev
npm install express --save-dev
Copy the code

Step 1: Server build (webSocketServer.js)

const webSocket = require("ws"); Const ws = new websocket. Server({port: 8000}); // create server with port 8000 let clients = {}; let clientNum = 0; Ws. on("connection", (client) => {// Connect to the client // assign the number of the client, that is, the user to participate in the chat client.name = ++clientNum; clients[client.name] = client; On ("message", (MSG) => {console.log(" user "+ client.name +" say :" + MSG); // Broadcast data output broadcast(client, MSG); }); Client. On ("error", (err) => {if (err) {console.log(err); }}); On ("close", () => {delete clients[client.name]; Console. log(" user "+ client.name +" offline ~~"); }); }); Function broadcast(client, MSG) {for (var key in clients) {clients[key]. Send (" client "+ client. }}Copy the code

Step 2: Client-side static server build (server.js)

const express = require("express"); // Const path = require("path"); Const app = express(); const port = 3000; // port const host = "127.0.0.1"; Use (express. Static (path.resolve(__dirname, "./client"))); / / set to the path of the open service app. Listen (port, host, () = > {/ / monitor service console. The log (` client server: http://${host} : ${port} `); });Copy the code

Step 3: Client page building (index.html)

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta HTTP-equiv =" x-UA-compatible "content=" IE =edge"> <title> client </title> </head> <body>  <div id="content" name="name" style="overflow-y: scroll; width: 400px; height: 300px; border: solid 1px #000"></div> <br /> <div> <input type="text" id="msg" style="width: 200px;" </div> <button id="submit" </button> <script SRC =" wsclient.js "charset=" utF-8 "></script> <script> document.querySelector('#submit').addEventListener('click', function () { var msg2 = msg.value ws.send(msg2) msg.value = '' }, false) </script> </body> </html>Copy the code

Step 4: Client connect to server configuration (wsclient.js)

Const ws = new WebSocket("ws://127.0.0.1:8000"); / / to connect to the client / / online ws onopen () = = > {ws. Send (" I'm online "); }; Ws.onmessage = (MSG) => {const content = document.getelementById ("content"); content.innerHTML += msg.data + "<br>"; }; // Ws. onError = (err) => {console.log(err); }; Onclose = () => {console.log("close"); };Copy the code

We’re done here.

Step 5: Start webSocketserver. js and server.js respectively

node WebSocketServer.js
Copy the code

node server.js
Copy the code

The above represents successful startup. Next we have a local test. If you want to play online, you can upload it yourself.

🔥 4. View the effect

Open localhost:3000 in two browsers to see the effect:

Download code: codechina.csdn.net/qq_32442973…

Q: What if websocket is disconnected? (More on that later)

🔥 5. Recommend good articles in the past

  • How does NPM install come from the package? No wonder NPMJS has such a library! How to make your own NPM component library!
  • How wechat WeixinJSBridge. Invoke successful payment unexpectedly does not jump? And shut down my page! What should I do?
  • Talk about macro task and micro task in JS!
  • 2021 front-end interview JS topic summary, might as well have a look at the question belongs to you
  • The latest edition of Front-end Asynchronous Solutions (2021)_ Paper Plane Blog
  • Use Docker deployment front-end project combat tutorial, the pit I help you step on! _ Paper Plane Blog -CSDN blog