My Socket web chat server does not show messages sent by users

Moreover, all the rooms are created and users can connect to the rooms, but when I send a message, the message is not sent. It is programmed in my code so that when a new user joins the room, the message you joined is sent so that others can see it, some kind of “John” and he can send messages and others also saw this but for some reason it doesn’t happen, what could this be connected with?

screenshot 1

screenshot 2

screenshot 3

Server js
`
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
app.set('views', './views');
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));

const rooms = {};

app.get("https://stackoverflow.com/", (req, res) => {
res.render('index', { rooms: rooms });
});

app.post('/room', (req, res) => {
if (rooms[req.body.room] != null) {
return res.redirect("https://stackoverflow.com/");
}
rooms[req.body.room] = { users: {} };
res.redirect(req.body.room);
//Send message that a new room was created
io.emit('room-created', req.body.room);
});

app.get('/:room', (req, res) => {
if (rooms[req.params.room] == null) {
return res.redirect("https://stackoverflow.com/");
}
res.render('room', { roomName: req.params.room });
});

server.listen(8080);

io.on('connection', socket => {
socket.on('new-user', (room, name) => {
socket.join(room);
rooms[room].users[socket.id] = name;
socket.to(room).broadcast.emit('user-connected', name);
});
socket.on('send-chat-message', (room, message) => {
socket.to(room).broadcast.emit('chat-message', { message: message, name:rooms[room].users[socket.id]            
});
socket.on('disconnect', () => {
getUserRooms(socket).forEach(room => {
socket.to(room).broadcast.emit('user-disconnected', rooms[room].users[socket.id]);
delete rooms[room].users[socket.id];
});
});
});
function getUserRooms(socket) {
return Object.entries(rooms).reduce((names, [name, room]) => {
if (room.users[socket.id] != null) names.push(name);
return names;
}[]);
}
`

/public/Script.js

`
const socket = io('http://vps.mydomen.com:8080')
const messageContainer = document.getElementById('message-container')
const roomContainer = document.getElementById('room-container')
const messageForm = document.getElementById('send-container')
const messageInput = document.getElementById('message-input')

if (messageForm != null) {
const name = prompt('What is your name?')
appendMessage('You joined')
socket.emit('new-user', roomName, name)

messageForm.addEventListener('submit', e => {
e.preventDefault()
const message = messageInput.value
appendMessage(`You: ${message}`)
socket.emit('send-chat-message', roomName, message)
messageInput.value=""
})
}

socket.on('room-created', room => {
const roomElement = document.createElement('div')
roomElement.innerText = room
const roomLink = document.createElement('a')
roomLink.href = `/${room}`
roomLink.innerText="join"
roomContainer.append(roomElement)
roomContainer.append(roomLink)
})

socket.on('chat-message', data => {
appendMessage(`${data.name}: ${data.message}`)
})

socket.on('user-connected', name => {
appendMessage(`${name} connected`)
})

socket.on('user-disconnected', name => {
appendMessage(`${name} disconnected`)
})

function appendMessage(message) {
const messageElement = document.createElement('div')
messageElement.innerText = message
messageContainer.append(messageElement)
}
`
Client js
`
const socket = io('vps.mydomen.com:8081');

socket.on('message', msg => {
console.log(msg); 
});

document.querySelector('button').onclick = () => {
const msg = document.querySelector('input').value;
socket.emit('message', msg); 
}

`

/views/index.ejs

`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Chat App</title>
<script defer src="vps.mydomen.com:8080/socket.io/socket.io.js"></script>
<script defer src="script.js"></script>
</head>
<body>
<div id="room-container">
<% Object.keys(rooms).forEach(room => { %>
<div><%= room %></div>
<a href="/<%= room %>">Join</a>
<% }) %>
</div>
<form action="/room" method="POST">
<input name="room" type="text" required>
<button type="submit">New Room</button>
</form>
</body>
</html>
`

/views/room/room.ejs
`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Chat App</title>
<script>
const roomName = "<%= roomName %>"
</script>
<script defer src="vps.mydomen.com:8080/socket.io/socket.io.js"></script>
<script defer src="script.js"></script>
<style>
body {
padding: 0;
margin: 0;
display: flex;
justify-content: center;
}

#message-container {
width: 80%;
max-width: 1200px;
}

#message-container div {
background-color: #CCC;
padding: 5px;
}

#message-container div:nth-child(2n) {
background-color: #FFF;
}

#send-container {
position: fixed;
padding-bottom: 30px;
bottom: 0;
background-color: white;
max-width: 1200px;
width: 80%;
display: flex;
}

#message-input {
flex-grow: 1;
}
</style>
</head>
<body>
<div id="message-container"></div>
<form id="send-container">
<input type="text" id="message-input">
<button type="submit" id="send-button">Send</button>
</form>
</body>
</html>
`

All the modules I need are installed. We are a VPS server I connected to my domain (vps.mydomain.com)

My vps server runs on port 8080, you can see this in my code

  • 1

    Please remember to read the posting guidelines and edit your post accordingly. Use proper markdown, do not post images of text (post that text), and post minimal reproducible example code (don’t include things that don’t matter to the problem. Your HTML and CSS, for example, have effectively nothing to do with a websocket problem). What does matter is what the browser tells you: any console errors? Any network errors? (dev tools have a dedicated websocket filter so you can see what gets sent and received: what does happen there?)

    – 




  • Server doesn’t show error, it does not show any errors in the logs, there are no errors either, the chat messages and the inscription about the rejection of new users are simply not reproduced

    – 

  • 1

    Your post has to stand on its own: all the details, and all the code (in minimal reproducible example form) should be in your post, and be enough information for folks to help answer your problem (and forming that minimal reproducible example is a chore, but it’s important you run through it because 99.999% of the time, actually forming an MCVE makes you find the problem yourself. In the rare few cases folks don’t, that is now good code to put in your a post).

    – 




Leave a Comment