Node.js+express+socket realizes online real-time multi-person chat room

Node.js+express+socket realizes online real-time multi-person chat room

This article shares the specific code of Node.js+express+socket to realize online real-time multi-person chat room for your reference. The specific content is as follows

The file structure is as follows:

Front-end part:

Login page Login part:

login.html

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

<head>  
    <meta charset="UTF-8">  
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">  
    <meta http-equiv="X-UA-Compatible" content="ie=edge">  
    <title>login</title>  
    <link rel="stylesheet" href="css/login.css" >  
</head> 

<body>  
    <div class="login-box flex-box">  
        <!--Login title bar-->  
        <h2 class="sign-title box-width">LOGIN</h2>  
        <!--Avatar Bar-->  
        <div class="picture-carousel">  
            <div class="arrow left-arrow">  
                <div class="before-arrow"></div>  
            </div>  
            <img class="p1 img-setting" src="./img/1.jpg" alt="1.jpg">  
            <img class="p2 img-setting" src="./img/2.jpg" alt="2.jpg">  
            <img class="p3 img-setting" src="./img/3.jpg" alt="3.jpg">  
            <img class="p2 img-setting" src="./img/4.jpg" alt="4.jpg">  
            <img class="p1 img-setting" src="./img/5.jpg" alt="5.jpg">  
            <div class="arrow right-arrow">  
                <div class="after-arrow"></div>  
            </div>  
        </div>  
        <!--Username column-->  
        <div class="name-box box-width">  
            <input type="text" class="user-name box-width" placeholder="Please Type Your Name">  
        </div>  
        <!--Confirmation column-->  
        <div class="button-box box-width">  
            <input type="button" class="login-button box-width" value="Login The Chatroom">  
        </div>  
        <!--Error message column-->  
        <div class="error-box box-width">  
            <span class="error-message">Welcome to chatroom!</span>  
        </div>  
    </div>  
</body>  
<script src="js/login.js"></script> 

</html>

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;  
} 


/*Image switch*/ 

.picture-carousel {  
    position: relative;  
    display: flex;  
    margin: 10%;  
} 


/*Image switching 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 transparent 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(0.6);  
    z-index: 1;  
} 

.p1:hover {  
    transform: scale(0.8);  
} 

.p2 {  
    transform: scale(0.8);  
    z-index: 2;  
} 

.p2:hover {  
    transform: scale(1);  
} 

.p3 {  
    transform: scale(1);  
    z-index: 3;  
} 

.p3:hover {  
    transform: scale(1.2);  
} 


/*username*/ 

.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 0 20px;
}

.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 left arrow listener event leftArrow.addEventListener('click',function(){
    imgArray.unshift(imgArray[imgArray.length - 1]); // Add an element to the beginning of the array //  
    imgArray.pop(); // Delete and return the last element of the array carouselImg(); // Switch pictures });

// Add right arrow listener event rightArrow.addEventListener('click',function(){
    imgArray.push(imgArray[0]); // Put the first element at the end imgArray.shift(); // Delete and return the first element of the array carouselImg(); // Switch pictures });

// Switch pictures function carouselImg(){
    for(var count = 0; count < imgArray.length; count++){
        document.getElementsByTagName('img')[count].src = './img/' + imgArray[count] + '.jpg';
        document.getElementsByTagName('img')[count].alt=imgArray[count] + '.jpg';
    }
}

// Add login button listener event loginButton.addEventListener('click',function(){
    if(userName.value === ''){
        errorMessage.innerHTML = 'Please Type You Name';
        errorMessage.style.visibility = 'visible';
    }else if(userName.value.length > 8){
        errorMessage.innerHTML = '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 key binding login event document.onkeydown = function (event) {  
    var e = event || window.event;  
    if(e && e.keyCode === 13){
        loginButton.click();
    }
};

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>chat-room</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="./css/index.css" />
</head>
<body>
    <div class="chat-box">
        <!-- Chat Box Header-->
        <div class="chat-header">
            <div class="button-box">
                <input type="button" class="log-out" value="LOGOUT" />
            </div>
        </div>
        <!-- Chat box body-->
        <div class="chat-body">
            <!-- Left side of the chat box -->
            <div class="chat-body-left">
                <!-- Chat content on the left side of the chat box-->
                <div class="chat-content"></div>
                <!-- Chat input box on the left side of the chat box-->
                <div class="chat-edit">
                    <input type="text" class="edit-box" placeholder="Please Type You Message" maxlength="15"/>
                    <input type="button" class="edit-button" value="SEND" />
                </div>
            </div>
            <!-- Right side of the chat box -->
            <div class="chat-body-right">
                <!-- Count the number of people on the right side of the chat box-->
                <div class="online-count">Online:0</div>
                <!-- Username on the right side of the chat box -->
                <div class="user-name">user-name</div>
                <!-- Avatar on the right side of the chat box-->
                <img class="user-img" />
            </div>
        </div>
    </div>
</body>
</html>

<script src="./js/socket.io.js"></script>
<script src="./js/index.js"></script>

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(-135deg,#51D15B,#42A855);
    background: -moz-linear-gradient(-135deg,#51D15B,#42A855);
    background: -webkit-linear-gradient(-135deg,#51D15B,#42A855);
    background: -o-linear-gradient(-135deg,#51D15B,#42A855);
}

/* Outermost layer */
.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;
}

/* Content on the left */
.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 with small screens */
@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 content of url var url = decodeURI(location.href).split('?')[1].split('&'); //..The first element of the array is the image 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('edit-button')[0];

// Get the username column var userName = document.getElementsByClassName('user-name')[0];

// Get the number of online people column var onlineCount = document.getElementsByClassName('online-count')[0];

// The name of the login page is placed on the right userName.innerHTML = url[1].split('=')[1];
var userImg = document.getElementsByClassName('user-img')[0];

// Put the avatar of the login page on the right userImg.src = `./img/${url[0].split('=')[1]}`;
var logOut = document.getElementsByClassName('log-out')[0];

// Send button to bind click event editButton.addEventListener('click',sendMessage);

// Logout button bind click event logOut.addEventListener('click',closePage);

// Bind the Enter key and send events 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's Firefox or Google window.location.href = "about:blank";
    }else{
        window.opener = null;
        window.open("","_self");
        window.close();
    }
}

// socket part var socket = io();

// Generate a chat bubble when a message is received and it is not local socket.on('message',function(information){
    console.log('Received message',information);
    if(information.name !== userName.textContent){ // Not local createOtherMessage(information); // Generate a chat bubble}
});

// When someone connects to the socket, socket.on('connected', function(onlinecount) {
    console.log(`Someone is logged in, the number of people online is: ${onlinecount}`);
    onlineCount.innerHTML = 'Online:' + onlinecount;
});

// When receiving a disconnection, socket.on('disconnected', function(onlinecount){
    console.log(`Someone disconnected: Current number of people: ${onlinecount}`);
    onlineCount.innerHTML = 'Online:' + onlinecount;
});

//Send the local message function sendMessage(){
    if(editBox.value != ''){ //..if the content sent is not empty var myInformation = {
            name :userName.textContent,
            chatContent : editBox.value,
            img : userImg.src
        };
        socket.emit('message',myInformation);
        createMyMessage(); // Create a native chat bubble editBox.value = ''; //..clear the text box}
}

// Generate a 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.innerHTML = 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.innerHTML= userName.textContent;
    userInformation.appendChild(userChatImg);
    userInformation.appendChild(userChatName);
    myMessageBox.appendChild(userInformation);

    chatContent.appendChild(myMessageBox);

    chatContent.scrollTop = chatContent.scrollHeight; // Scroll to the latest chat content}

// Generate chat bubbles for 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';  
    userChatName.innerHTML = 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.innerHTML = information.chatContent;  
    otherMessageContent.appendChild(text);  
    otherMessageBox.appendChild(otherMessageContent); 

    chatContent.appendChild(otherMessageBox); 

    chatContent.scrollTop = chatContent.scrollHeight;  
}

server.js

// Import must be ambiguous var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require('path');

// Online number statistics var onlineCount = 0;
app.use(express.static(__dirname));

// Path mapping app.get('/login.html',function(request,response){
    response.sendFile('login.html');
});

// When a user connects io.on('connection',function(socket){
    console.log('a user connected');

    //Send the number of online users to the client io.emit('connected',++onlineCount);

    // When a user disconnects socket.on('disconnect',function(){

            console.log('user disconnected');

            //Send to the number of clients io.emit('disconnected',--onlineCount);
            console.log(onlineCount);
    });

    // Received the message from the client socket.on('message',function(message){
        //Send a message to the client console.log('The message received by the server is:',message);
        io.emit('message',message);
    });
});

var server = http.listen(4000,function(){
    console.log('Server is running');
});

at last

Terminal Input

node server.js

Enter the browser address bar

http://localhost:4000/login.html

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Detailed explanation of the key points of Python Socket programming
  • Websocket+Vuex implements a real-time chat software
  • Java Socket to implement multi-person chat system
  • Springboot Websocket Stomp message subscription push
  • Java Socket simulation to realize chat room
  • C++ implements network chat room based on socket multithreading
  • Implementing simple chat room dialogue based on websocket
  • C language socketpair usage case explanation

<<:  MySQL 8.0.16 Win10 zip version installation and configuration graphic tutorial

>>:  Implementation of Docker cross-host network (overlay)

Recommend

JS implements the sample code of decimal conversion to hexadecimal

Preface When we write code, we occasionally encou...

Detailed use cases of vue3 teleport

Official Website https://cli.vuejs.org/en/guide/ ...

Comprehensive summary of MYSQL tables

Table of contents 1. Create a table 1.1. Basic sy...

JavaScript to implement the web version of the snake game

This article shares the specific code for JavaScr...

Deploy Varnish cache proxy server based on Centos7

1. Varnish Overview 1. Introduction to Varnish Va...

HTML Frameset Example Code

This article introduces a framework made by Frame...

HTML Nine-grid Layout Implementation Method

Diversifying website layouts is our front-end spe...

Getting Started Tutorial for Beginners ④: How to bind subdirectories

To understand what this means, we must first know ...

Mysql sql slow query monitoring script code example

1. Modify my.cnf #The overall effect is that both...

Basic commands for MySQL database operations

1. Create a database: create data data _name; Two...

Several ways to add timestamps in MySQL tables

Scenario: The data in a table needs to be synchro...

jQuery treeview tree structure application

This article example shares the application code ...

Examples of using provide and inject in Vue2.0/3.0

Table of contents 1. What is the use of provide/i...

Detailed explanation of how to view the current number of MySQL connections

1. View the detailed information of all current c...

Component design specifications for WeChat mini-program development

WeChat Mini Program Component Design Specificatio...