Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize online Real-time Multi-person chat Room with Node.js+express+socket

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article, the editor introduces in detail "how to achieve online real-time multi-person chat room in Node.js+express+socket". The content is detailed, the steps are clear, and the details are handled properly. I hope that this article "how to achieve online real-time multi-person chat room in Node.js+express+socket" can help you solve your doubts.

The file structure is as follows:

Front end:

Login section of the login page:

Login.html

Login LOGIN

1.jpg

2.jpg

3.jpg

4.jpg

5.jpg

Welcome to chatroom!

Login.css

* {padding: 0; margin: 0; font-family: "Microsoft Yahei";} html, body {width: 100%; height: 100%; font-family: "Microsoft Yahei"; display: flex; justify-content: center; align-items: center;} body {background: linear-gradient (- 135deg, # 51D15B, # 42A855) Background:-moz-linear-gradient (- 135deg, # 51D15B, # 42A855); background:-webkit-linear-gradient (- 135deg, # 51D15B, # 42A855); background:-o-linear-gradient (- 135deg, # 51D15B, # 42A855);} .flex-box {display: flex; justify-content: center; align-items: center;}. Box-width {width: 80 } / * outermost layer * / .login-box {width: 20%; min-width: 304px; max-width: 404px; height: 50%; min-height: 368px; max-height: 468px; flex-direction: column; box-shadow: 1px 1px 15px # 7B8C99; background: # fff;} / * LOGIN title * / .sign-title {color: # 42A855 Border: 2px solid # 42A855; border-top: transparent; border-left: transparent; border-right: transparent;} / * picture-carousel {position: relative; display: flex; margin: 10%;} / * Arrow * / .arrow {z-index: 3; position: absolute; font-size: 60px; height: 100% Width: 30%; display: flex; justify-content: center; align-items: center; color: # ffffff;} .arrow: hover {cursor: pointer;}. Left-arrow {left: 0;} .before-arrow {width: 0px; height: 0px; border-width: 30px; border-style: solid; border-color: transparent # 51D15B transparent transparent Right-arrow {right: 0;}. After-arrow {width: 0px; height: 0px; border-width: 30px; border-style: solid; border-color: transparent # 51D15B;} .picture-carousel img {width: 80px; height: 80px; transition: all 0.2s linear;-moz-transition: all 0.2s ease-out -webkit-transition: all 0.2s ease-out;-o-transition: all 0.2s ease-out;}. Img-setting {margin: 0px-15px;} .p1 {transform: scale; z-index: 1;} .p1: hover {transform: scale;} .p2 {transform: scale; z-index: 2 } .p2: hover {transform: scale (1);} .p3 {transform: scale (1); z-index: 3;} .p3: hover {transform: scale (1.2);} / * user name * / .name-box {display: flex; justify-content: center; border: 1px solid # 51D15B;} .name-box. User-name {width: 100% Text-align: center; padding: 10px; outline-color: # 42A855; border: none; font-size: 16px;} / * login button * / .button-box {display: flex; justify-content: center; margin: 10px 020px;} .button-box. Login-button {width: 100%; padding: 10px 20px; outline:none; border: none; background: # 42A855 Color: white; font-size: 16px;} / * error message * / .error-box {color: # 42A855; border: 2px solid # 42A855; border-top: transparent; border-left: transparent; border-right: transparent;}. Error-box span {visibility: hidden; color: # d43f3a; font-size: 14px;}

Login.js

/ used to store the order of pictures var imgArray = ["1", "2", "3", "4", "5"]; / / get the arrow var leftArrow = document.getElementsByClassName ("left-arrow") [0]; var rightArrow = document.getElementsByClassName ("right-arrow") [0]; / / get the user name var userName = document.getElementsByClassName ("user-name") [0]; / / get the login button var loginButton = document.getElementsByClassName ("login-button") [0] / / get the error message bar var errorMessage = document.getElementsByClassName ("error-message") [0]; / / add the left arrow listening event leftArrow.addEventListener ("click", function () {imgArray.unshift (imgArray [imgArray.length-1]); / / add an element / / imgArray.pop () to the beginning of the array; / / delete and return the last element of the array carouselImg () / / switch picture}); / / add right arrow listening event rightArrow.addEventListener ("click", function () {imgArray.push (imgArray [0]); / / put the first element on the last imgArray.shift (); / / delete and return the first element of the array carouselImg (); / / switch picture}) / / switch picture function carouselImg () {for (var count = 0 position count)

< imgArray.length;count++){ document.getElementsByTagName("img")[count].src = "./img/" + imgArray[count] + ".jpg"; document.getElementsByTagName("img")[count].alt=imgArray[count] + ".jpg"; }}// 添加登录按钮监听事件loginButton.addEventListener("click",function(){ if(userName.value === ""){ errorMessage[xss_clean] = "Please Type You Name"; errorMessage.style.visibility = "visible"; }else if(userName.value.length >

8) {errorMessage [XSS _ clean] = "Your Name Cannot Over 8 Words"; errorMessage.style.visibility = "visible";} else {_ window.location.href=encodeURI ("index.html?selectpicture=" + document.getElementsByClassName ("p3") [0] .alt + "& username=" + userName.value);}}) / / Enter button binds login event _ document.onkeydown = function (event) {var e = event | | window.event; if (e & & e.keyCode = 13) {loginButton.click ();}}

Index.html

Chat-room Online:0 user-name

Index.css

* {margin: 0; padding: 0; font-family: "Microsoft Yahei"} html,body {width: 100%; height: 100%;} / * background color * / body {display: flex; justify-content: center; align-items: center; background: linear-gradient (- 135degr / 51D15B camera / 42A855); background:-moz-linear-gradient (- 135degmt 51D15B / 42A855) Background:-webkit-linear-gradient (- 135degmeme 51D15B Encyclopedia 42A855); background:-o-linear-gradient (- 135degmeme / 51D15B Ensemble 42A855);} / * outermost * / .chat-box {width: 50%; max-width: 720px; min-width: 400px; height: 80%; min-height: 530px; max-height: 530px; display: flex; flex-direction: column; background: # fff Box-shadow: 1px 1px 15px # 333;} / * header * / .chat-header {margin: 5px; box-shadow: 1px 1px 15px # 7B8C99;} .button-box {display: flex; justify-content: flex-end;}. Log-out {height: 100%; font-size: 14px; font-weight: bold; padding: 5px 15px; color: # 79C2EA; background: # fff; outline: none; border: none Border-radius: 15px; cursor: pointer;} / * body * / .chat-body {height: 90%; display: flex; flex-direction: row; justify-content: space-around; align-items: center; margin: 5px; padding: 5px;} / * left side of the body * / .chat-body-left {height: 100%; width: 70%; display: flex; flex-direction: column Justify-content: space-around; margin: 5px;} / * left content * / .chat-content {box-shadow: 1px 1px 15px # 7B8C99; height: 100%; margin-bottom: 5px; overflow: scroll;} / * chat bubble * / .my-message-box {display: flex; justify-content: flex-end; align-content: center; margin: 5px } .other-message-box {display: flex; justify-content: flex-start; align-content: center; margin: 5px;} .message-content {display: flex; justify-content: center; align-content: center; background-color: # 51D15B; padding:5px 10px; border-radius: 15px; color: # fff;} .other-message-content {display: flex Justify-content: center; align-content: center; background-color: # 79C2EA; padding: 5px 10px; border-radius: 15px; color: # fff;}. Message-content span {padding:20px 0px;} .user-chat-img {width: 50px; height: 50px;} .other-message-content span {padding:20px 0px;} .message-arrow {width: 0; height: 0; border-width:8px Border-style: solid; border-color: transparent transparent transparent # 51D15B; align-self: center;} .other-message-arrow {width: 0; height: 0; border-width: 8px; border-style: solid; border-color: transparent # 79C2EA transparent transparent; align-self: center;}. User-information {display: flex; flex-direction: column; align-content: flex-end;} .other-user-information {display: flex Flex-direction: column; align-content: flex-end;} .user-chat-name {color: # 333; font-size: 16px; text-align: center;} / * chat input box * / .chat-edit {margin-top: 5px; display: flex; justify-content: space-between; align-items: center; box-shadow: 1px 1px 15px # 7B8C99; overflow: hidden } / * chat input box input area * / .edit-box {width: 80%; height: 100%; margin: 5px; border: none; outline: none;} / * chat input box button * / .edit-button {height: 100%; padding: 5px 15px; background: # fff; color: # 79C2EA; outline: none; border: none; border-radius: 15px; cursor: pointer Font-size: 14px; font-weight: bold;} / * right side of the body * / .chat-body-right {height: 100%; width: 30%; display: flex; flex-direction: column; justify-content: center; align-items: center; margin: 5px; box-shadow: 1px 1px 15px # 7B8C99;}. User-name {margin: 15px; font-size: 18px; font-weight: bold; color: # 79C2EA }. User-img {width: 100px; height: 100px; margin: 5px;} .online-count {font-size: 18px; font-weight: bold; color: # 79C2EA;} / * compatible small screen * / @ media screen and (max-width:420px) {. Chat-box {width: 50%; max-width: 720px; min-width: 300px; height: 80% Min-height: 530px; max-height: 530px;} .chat-body-left {height: 100%; width: 100%; display: flex; flex-direction: column; justify-content: space-around; margin: 5px;} .chat-body-right {display: none;}}

Index.js

/ / get the contents of url var url = decodeURI (location.href) .split ("?") [1] .split ("&"); / /. The first element of the array is the picture path, and the second element is the user name console.log (url); / / get the chat content box var chatContent = document.getElementsByClassName ("chat-content") [0]; / / get the chat input box var editBox = document.getElementsByClassName ("edit-box") [0]; / / get the chat input box send button var editButton = document.getElementsByClassName ("chat") [0] / / get the username column var userName = document.getElementsByClassName ("user-name") [0]; / / get the online headcount bar var onlineCount = document.getElementsByClassName ("online-count") [0]; / / put the name of the login page on the right side of username [XSS _ clean] = url [1] .split ("=") [1]; var userImg = document.getElementsByClassName ("user-img") [0] / / put the avatar of the login page on the right side userImg.src = `. / img/$ {url [0] .split ("=") [1]}`; var logOut = document.getElementsByClassName ("log-out") [0]; / / send button bind click event editButton.addEventListener ("click", sendMessage); / / logout button bind click event logOut.addEventListener ("click", closePage) / / bind Enter key and send event _ document.onkeydown = function (event) {var e = event | | window.event; if (e & & e.keyCode = 13) {if (editBox.value! = ") {editButton.click ();}; / / close the page function closePage () {var userAgent= navigator.userAgent; console.log (`userAgent=$ {userAgent} `) If (userAgent.indexOf ("Firefox")! =-1 | | userAgent.indexOf ("Chrome")! =-1) {/ / If it is Firefox or Google _ window.location.href = "about:blank";} else {window.opener = null; window.open ("", "_ self"); window.close ();}} / / socket part var socket = io () / generate chat bubble socket.on ("message", function (information) {console.log ("received message", information); if (information.name! = = userName.textContent) {/ / createOtherMessage (information) when not native; / / generate chat bubble} when a message is received and is not local) / / when receiving someone to connect to socket.on ("connected", function (onlinecount) {console.log (`someone logged in, the number of people online is ${onlinecount} `); onlineCount [XSS _ clean] = "Online:" + onlinecount;}); / / when receiving someone to disconnect, socket.on ("disconnected", function (onlinecount) {console.log (`someone disconnected: current number: ${onlinecount}`) OnlineCount [XSS _ clean] = "Online:" + onlinecount;}); / / send the native message function sendMessage () {if (editBox.value! = ") {/ /.. If the message is not empty var myInformation = {name: userName.textContent, chatContent: editBox.value, img: userImg.src}; socket.emit ("message", myInformation); createMyMessage (); / / create native chat bubble editBox.value = "; / /.. Clear text box}} / / generate native chat bubble function createMyMessage () {var myMessageBox = document.createElement ("div"); myMessageBox.className = "my-message-box"; var messageContent = document.createElement ("div"); messageContent.className = "message-content"; var text = document.createElement ("span"); text [XSS _ clean] = editBox.value; messageContent.appendChild (text); myMessageBox.appendChild (messageContent) Var arrow = document.createElement ("div"); arrow.className = "message-arrow"; myMessageBox.appendChild (arrow); var userInformation = document.createElement ("div"); userInformation.className = "user-information"; var userChatImg = document.createElement ("img"); userChatImg.className = "user-chat-img"; userChatImg.src = userImg.src; var userChatName = document.createElement ("div"); userChatName.className = "user-chat-name" UserChatName [XSS _ clean] = userName.textContent; userInformation.appendChild (userChatImg); userInformation.appendChild (userChatName); myMessageBox.appendChild (userInformation); chatContent.appendChild (myMessageBox); chatContent.scrollTop = chatContent.scrollHeight; / / scroll to the latest chat} / / generate chat bubbles of other users function createOtherMessage (information) {var otherMessageBox = document.createElement ("div"); otherMessageBox.className = "other-message-box" Var otherUserInformation = document.createElement ("div"); otherUserInformation.className = "other-user-information"; var userChatImg = document.createElement ("img"); userChatImg.className = "user-chat-img"; userChatImg.src = information.img; var userChatName = document.createElement ("span"); userChatName.className = "user-chat-name"; username [XSS _ clean] = information.name; otherUserInformation.appendChild (userChatImg) OtherUserInformation.appendChild (userChatName); otherMessageBox.appendChild (otherUserInformation); var otherMessageArrow = document.createElement ("div"); otherMessageArrow.className = "other-message-arrow"; otherMessageBox.appendChild (otherMessageArrow); var otherMessageContent = document.createElement ("div"); otherMessageContent.className = "other-message-content"; var text = document.createElement ("span"); text[ XSS _ clean] = information.chatContent; otherMessageContent.appendChild (text) OtherMessageBox.appendChild (otherMessageContent); chatContent.appendChild (otherMessageBox); chatContent.scrollTop = chatContent.scrollHeight;}

Server.js

/ / introduce necessary var express = require ("express"); var app = express (); var http = require ("http") .Server (app); var io = require ("socket.io") (http); var path = require ("path"); / / online headcount var onlineCount = 0 X app.use (express.static (_ dirname); / / path mapping app.get ("/ login.html", function (request,response) {response.sendFile ("login.html")) }); / / io.on ("connection", function (socket) {console.log ("a user connected"); / / number of online users sent to clients io.emit ("connected", + + onlineCount); / / when users disconnect socket.on ("disconnect", function () {console.log ("user disconnected") / / number of clients sent to io.emit ("disconnected",-- onlineCount); console.log (onlineCount);}); / / received a message from the client socket.on ("message", function (message) {/ / send a message console.log to the client ("the message received by the server is:", message) Io.emit ("message", message);}); var server = http.listen (4000) function () {console.log ("Server is running");})

Last

Terminal input

Node server.js

Browser address bar input

Http://localhost:4000/login.html

After reading this, the article "how to realize online real-time multi-person chat room with Node.js+express+socket" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report