I know it sounds ridiculous but believe me guys
The chat app that I am making with socket.io has a problem that first when all the users log in it displays the log in message and also after that when anybody posts a message it displays the message but multiple times with all the usernames active in the chat room even if anyone hasn’t posted the message,
I am a newbie to node.js & socket.io btw,
I would be really grateful if somebody could help me with my problem,
Below are my codes if you want to test the app yourselves and suggest me the proper ways of doing it and fixing the problem,
Sevrer.js –
const express = require('express');
const app = express();
const { Server } = require('socket.io');
const http = require('http');
const server = http.createServer(app);
const io = new Server(server);
const port = 80;
const path = require('path');
app.use(express.static(path.join(__dirname,'public')));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
// Now let's move to the socket io part
io.on('connection', (socket) => {
socket.on('new-user', (username) => {
//users[socket.id] = username;
console.log(`${username} just connected to the server!`);
io.emit('connected-user', username)
socket.emit('user-connected',username)
// console.log("A new user just connected!");
})
socket.on('senders-name',(username) => {
socket.broadcast.emit('name',username);
//socket.removeAllListeners('senders-name',username);
})
socket.on('send message',(chat) => {
socket.broadcast.emit('the-msg',chat);
/*socket.on('senders-name',(username) => {
socket.broadcast.emit('name',username);
})*/
console.log(`Sender sent this message : ${chat}`);
})
socket.on('send-time',(time) => {
socket.broadcast.emit('time',time);
console.log(time);
})
socket.on('send-date',(date) => {
socket.broadcast.emit('date',date);
console.log(date);
})
socket.on('disconnect',(username) => {
//io.emit('disconnected-user',users[socket.id]);
// users[socket.id] = username;
socket.broadcast.emit('user-disconnect',username);
io.emit('user-disconnect',username);
console.log(`${username} just left!`);
//delete users[socket.id];
})
})
server.listen(port, () => {
//console.log(`Server is listening at the https://localhost:${port}/`);
console.log(`Server is listening at the https://localhost/`);
});
Script.js –
const socket = io();
const sendBtn = document.getElementById("send");
const form = document.getElementById("forms");
const messageInput = document.getElementById("msgs");
const chatWindow = document.getElementById("chat-window");
const joinBtn = document.getElementById("join");
const refreshBtn = document.getElementById("ref");
const usernameInput = document.getElementById("username");
const bg = document.getElementById("bg");
const userForms = document.getElementById("user-form");
var date = new Date();
var current_date = date.getDate()+"/"+(date.getMonth() + 1)+'/'+date.getFullYear();
var current_time = date.getHours()+":"+date.getMinutes();
joinBtn.addEventListener("click",(e) => {
e.preventDefault();
if(usernameInput.value === ''|usernameInput.value == null){
alert("An username is required before entering the chat!");
}
else{
bg.style.opacity = '0';
bg.style.pointerEvents = 'none';
// Now lets obtain the user field's value
const val = usernameInput.value;
socket.emit('new-user',val);
socket.emit('user-left',val)
}
});
userForms.addEventListener('submit',(e) => {
e.preventDefault();
})
/*usernameInput.addEventListener('keydown',(e) => {
e.preventDefault();
if(keyCode = 13){
if(usernameInput.value === ''|usernameInput.value == null){
alert("An username is required before entering the chat!");
}
else{
bg.style.opacity = '0';
bg.style.pointerEvents = 'none';
// Now lets obtain the user field's value
const val = usernameInput.value;
socket.emit('new-user',val);
socket.emit('user-left',val)
socket.emit('senders-name',usernameInput.value);
}
}
})*/
document.addEventListener("close",(e) => {
const val = usernameInput.value;
socket.emit('user-left',val);
})
socket.on('connected-user', (username) =>{
const parentContainer = document.createElement('div');
parentContainer.className = 'join-info';
chatWindow.appendChild(parentContainer);
const user = document.createElement('p');
user.className = 'join';
user.innerText = `${username} joined the Chat!`;
parentContainer.appendChild(user);
});
socket.on('user-left', (username) => {
const parentContainer = document.createElement('div');
parentContainer.className = 'join-info';
chatWindow.appendChild(parentContainer);
const user = document.createElement('p');
user.className = 'join';
user.innerText = `${username} left the Chat!`;
parentContainer.appendChild(user);
})
sendBtn.addEventListener("click",(e) => {
//e.preventDefault();
if(messageInput.value === ''|messageInput.value == null){
e.preventDefault();
alert("First you need to type then click on send!");
}
})
form.addEventListener("submit",(e) => {
e.preventDefault();
if(messageInput.value){
//socket.emit('send message',messageInput.value);
socket.emit('send-time', current_time);
// socket.emit('senders-name',usernameInput.value);
//socket.emit('send-date', current_date);
const parent = document.createElement('div');
parent.className = 'parent';
chatWindow.appendChild(parent);
const chatMsg = document.createElement('div');
chatMsg.className = 'chat-msg';
parent.appendChild(chatMsg);
const msgInfo = document.createElement('div');
msgInfo.className = 'info';
chatMsg.appendChild(msgInfo);
const time = document.createElement('p');
time.className = 'time';
time.innerText = current_time;
msgInfo.appendChild(time);
const userName = document.createElement('p');
userName.className = 'time';
userName.innerText = usernameInput.value;
msgInfo.appendChild(userName);
const content = document.createElement('div');
content.className = 'content';
chatMsg.appendChild(content);
const msg = document.createElement('p');
msg.className = 'msg';
msg.innerText = messageInput.value;
content.appendChild(msg);
messageInput.value = '';
}
})
socket.on('name',username =>{
socket.on('the-msg',chat => {
const parent = document.createElement('div');
parent.className = 'parent1';
chatWindow.appendChild(parent);
const chatMsg = document.createElement('div');
chatMsg.className = 'chat-msg1';
parent.appendChild(chatMsg);
const msgInfo = document.createElement('div');
msgInfo.className = 'info1';
chatMsg.appendChild(msgInfo);
const userName = document.createElement('p');
userName.className = 'time1';
userName.innerText = username;
msgInfo.appendChild(userName);
const time = document.createElement('p');
time.className = 'time1';
time.innerText = current_time;
msgInfo.appendChild(time);
const content = document.createElement('div');
content.className = 'content1';
chatMsg.appendChild(content);
const msg = document.createElement('p');
msg.className = 'msg1';
msg.innerText = chat;
content.appendChild(msg);
messageInput.value = '';
})
})
function showUser(username){
const parentContainer = document.createElement('div');
parentContainer.className = 'join-info';
chatWindow.appendChild(parentContainer);
const user = document.createElement('p');
user.className = 'join';
user.innerText = `${username} joined the Chat!`;
parentContainer.appendChild(user);
}
function appendMessage(message){
const parent = document.createElement('div');
parent.className = 'parent';
chatWindow.appendChild(parent);
const chatMsg = document.createElement('div');
chatMsg.className = 'chat-msg';
parent.appendChild(chatMsg);
const msgInfo = document.createElement('div');
msgInfo.className = 'info';
chatMsg.appendChild(msgInfo);
const time = document.createElement('p');
time.className = 'time';
//time.innerText = Date();
msgInfo.appendChild(time);
const userName = document.createElement('p');
userName.className = 'time';
userName.innerText = message;
msgInfo.appendChild(userName);
const content = document.createElement('div');
content.className = 'content';
chatMsg.appendChild(content);
const msg = document.createElement('p');
msg.className = 'msg';
msg.innerText = message;
content.appendChild(msg);
messageInput.value = '';
}
styles.css –
*{
box-sizing: border-box;
padding: 0;
margin: 0;
}
html{
scroll-behavior: smooth;
scroll-padding-top: .5rem;
}
html,body{
margin: 0;
height: 100%;
}
body{
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
height: 100vh;
background: rgb(30,30,30);
font-family: system-ui,sans-serif;
}
button{
outline: none;
}
.chat-container{
border: none;
box-shadow: 0 10px 20px 0 rgba(0,0,0,.6);
padding: .2rem .3rem;
border-radius: .3rem;
height: 530px;
position: relative;
width: 400px;
display: flex;
overflow: hidden;
align-items: center;
justify-content: center;
background: linear-gradient(90deg,purple,74%,rgb(0, 81, 255));
}
.msgs-input{
position: absolute;
bottom: 2%;
width: 100%;
border: none;
display: flex;
justify-content: space-between;
padding: 0rem .3rem .2rem .5rem;
}
#forms{
display: flex;
align-items: center;
justify-content: space-between;
gap: 0px;
width: 100%;
border: none;
}
.msgs{
padding: .5rem 1rem;
border: none;
font-size: 1.15rem;
transition: all .3s;
border-top-left-radius: .3rem;
border-bottom-left-radius: .3rem;
outline: none;
width: 100%;
}
.msgs:hover{
background: #dedede;
}
.msgs:focus{
box-shadow: 0 0px 10px 0 rgba(0,0,0,.6);
}
.send{
padding: .5rem 1rem;
border: none;
font-size: 1.15rem;
border-top-right-radius: .3rem;
border-bottom-right-radius: .3rem;
width: 55px;
cursor: pointer;
transition: all .3s;
background: hsl(160, 84%, 31%);
color: #fff;
position: relative;
overflow: hidden;
outline: none;
}
.send > span {
position: absolute;
background: rgba(255,255,255,.5);
transform: translate(-50%, -50%);
pointer-events: none;
border-radius: 50%;
animation: rippleffect 1s linear infinite;
}
@keyframes rippleffect {
0% {
height: 0;
width: 0;
}
100% {
height: 500px;
width: 500px;
}
}
.send:hover{
background: hsl(160,84%,26%);
box-shadow: 0 0px 10px 0 rgba(0,0,0,.6);
}
.send:active{
scale: .98;
}
.chats{
border: none;
width: 100%;
height: 80%;
background: #2a2d2e;
border-radius: .3rem;
margin-bottom: 1rem;
padding: .3rem 1rem 2rem 1rem;
overflow: auto;
}
.default{
display: flex;
color: #fff;
align-items: center;
width: 100%;
justify-content: center;
height: 60vh;
}
.chat-header{
position: absolute;
display: flex;
align-items: center;
justify-content: space-between;
top: 0;
padding: .3rem 1rem;
color: #fff;
width: 100%;
}
.icon{
border:none;
width: fit-content;
font-size: 1.15rem;
padding: 5px;
border-radius: 50%;
}
.chat-msg1{
background: #eee;
padding: .3rem .5rem;
border-radius: .3rem;
width: 80%;
transition: all .2s;
cursor: default;
box-shadow: 0 10px 20px 0 rgba(0,0,0,.6);
}
.info1{
display: flex;
align-items: center;
justify-content: space-between;
}
.content1{
width: 100%;
margin-top: 1rem;
}
.chat-msg{
background: hsl(160, 93%, 36%);
padding: .3rem .5rem;
border-radius: .3rem;
width: 80%;
cursor: default;
transition: all .2s;
box-shadow: 0 10px 20px 0 rgba(0,0,0,.6);
}
.info{
display: flex;
align-items: center;
justify-content: space-between;
}
.content{
margin-top: 1rem;
}
.content,.content1{
width: 100%;
border: none;
padding: .5rem;
overflow-wrap: break-word;
}
.content1{
display: flex;
border: none;
align-items: flex-end;
justify-content: right;
}
.msg{
width: 100%;
}
.chat-msg1:hover{
background: hsl(0, 0%, 83%);
}
.chat-msg:hover{
background: hsl(160, 93%, 31%);
}
.parent{
display: flex;
flex-direction: column;
align-items: end;
border-radius: .3rem;
width: 100%;
background: transparent;
padding: .3rem 0rem;
margin-top: 1rem;
}
.parent1{
display: flex;
flex-direction: column;
align-items: start;
border-radius: .3rem;
width: 100%;
background: transparent;
padding: .3rem 0rem;
margin-top: 1rem;
}
.chat-msg1,.chat-msg{
animation: pop 1s ease-in-out;
}
@keyframes pop {
from{
scale: 0;
opacity: 0;
}
to{
scale: 1;
opacity: 1;
}
}
.join-info{
color: #fff;
background: #4b4d4e;
width: 100%;
font-size: 18px;
box-shadow: none;
cursor: default;
transition: all .3s;
padding: .5rem .5rem;
border-radius: .3rem;
margin-top: 1rem;
text-align: center;
}
.join-info:hover{
background: hsl(200, 2%, 27%);
}
#forms{
width: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.bg{
background: linear-gradient(rgba(0,0,0,.6),rgba(0,0,0,.75));
color: #fff;
width: 220px;
padding: .5rem 1rem 1.5rem 1rem;
border-radius: .3rem;
position: absolute;
box-shadow: 0 10px 20px 0 rgba(0,0,0,.75);
height: fit-content;
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
transition: all .3s ease-in-out;
z-index: 1;
}
.bg{
height: 100vh;
width: 100vw;
}
.prompt{
background: #2a2d2e;
color: #fff;
width: 220px;
padding: .5rem 1rem 1.5rem 1rem;
border-radius: .3rem;
box-shadow: 0 10px 20px 0 rgba(0,0,0,.6);
height: fit-content;
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
transition: all .5s ease-in-out;
z-index: 1;
}
.input-field{
width: 100%;
transition: all .5s ease-in-out;
}
.username{
outline: none;
width: 100%;
padding: .6rem 1rem .6rem .5rem;
font-size: .9rem;
border: none;
border-radius: .3rem;
transition: all .2s ease-in-out;
color: #000;
margin-bottom: 1rem;
}
.username:hover{
background: #dedede;
}
.username:focus{
box-shadow: 0 0px 20px 0 rgba(90, 106, 143, 0.6);
}
.btns{
display: grid;
grid-template-columns: repeat(2,1fr);
grid-gap: 10px;
transition: all .5s ease-in-out;
}
.done,.ref{
padding: .5rem 1rem;
transition: all .2s;
font-size: .9rem;
border: none;
background: #0385b1;
cursor: pointer;
color: #fff;
border-radius: .3rem;
}
.done:hover,.ref:hover{
transform: scale(0.95);
box-shadow: 0 5px 10px 0 rgba(0,0,0,.6);
}
.done:active,.ref:active{
scale: .9;
}
#user-form{
width: 100%;
}
@media (max-width: 400px) {
.chat-container{
width: 95%;
}
}
And finally the Html code –
<!DOCTYPE html>
<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>Node js Chat application</title>
<link rel="stylesheet" href="css/styles.css" />
<script src="https://kit.fontawesome.com/f3220d5256.js" crossorigin="anonymous"></script>
</head>
<body>
<div id="bg" class="bg">
<div class="prompt">
<div class="txt">
<p>
Please type your name here before entering the Chat
</p>
<br>
</div>
<div class="input-field">
<form id="user-form">
<input type="text" id="username" class="username" placeholder="Type Your Name here..." />
<br>
<div class="btns">
<button class="ref" type="reset" id="ref">Refresh</button>
<button class="done" type="submit" id="join">Join</button>
</div>
</form>
</div>
</div>
</div>
<div class="chat-container">
<div class="chat-header">
<div class="icon">
<i class="fa fa-comment"></i>
</div>
<div class="header">
<h3>
Blaze Chat Application
</h3>
</div>
<div class="status">
<p id="online">
Active
</p>
</div>
</div>
<div class="chats" id="chat-window">
<!--<div class="default">
<p>
No Messages Yet
</p>
</div>-->
<div class="parent1">
<div class="chat-msg1">
<div class="info1">
<p id="name1" class="name1">
Inferno (Bot)
</p>
<p id="time1" class="time1">
17:05
</p>
</div>
<div class="content1">
<p id="msg1">
Hello everyone! Welcome to the node js chatting application. Please don't misuse this application
for anything
</p>
</div>
</div>
</div>
<!--<div class="parent">
<div class="chat-msg">
<div class="info">
<p id="time" class="time">
17:07
</p>
<p id="name" class="name">
BlazeInferno64
</p>
</div>
<div class="content">
<p id="msg" class="msg">
Sure! I would keep a check on that in my server. Btw, this application is made on a pure node js based
server
</p>
</div>
</div>
</div>
<div class="join-info">
<p id="join" class="join">
BlazeInferno64 left the Chat!
</p>
</div>-->
</div>
<div class="msgs-input">
<form id="forms">
<input type="text" class="msgs" name="messages" id="msgs" placeholder="Type your message here..." />
<button type="submit" id="send" class="send">
<i class="fa fa-send"></i>
</button>
</form>
</div>
</div>
<script defer src="js/script.js"></script>
<script src="/socket.io/socket.io.js"></script>
</body>
</html>
I hope that someone could understand my problem and help me out please!
Please help me to find a fix for it