Home > Net >  Chat App - Socket.io - How do I display the message to other users?
Chat App - Socket.io - How do I display the message to other users?

Time:12-17

I'm building this chat app for a school project, and I followed multiple tutorials at the same time, that's what leaded me to this messy code, which I'm stuck with. At this point, when I user writes in a message and sends it, it is displayed for himself but no one else. So how do I get the message to be displayed to everyone? (note: I want to use a different css class for the messages received).

Client side code:

const socket = io('ws://localhost:8080');
const sendBtn = document.getElementById('sendBtn');
const messageInput = document.getElementById('messageInput');
const messagesContainer = document.getElementById('messagesContainer');
const chatBigContainer = document.getElementById('chatBigContainer');

sendBtn.addEventListener('click', () =>{
    if(messageInput.value === ""){
        return;
    } else {
        const text = messageInput.value;
        socket.emit('message', text);
    const divEl = document.createElement('div');
    divEl.className = "your-message";
    messagesContainer.appendChild(divEl);
    const labelEl = document.createElement('label');
    labelEl.innerHTML = "You";
    divEl.appendChild(labelEl);
    let messageSent = document.createElement('p');
    messageSent.innerHTML = text;
    divEl.appendChild(messageSent);

    messageInput.value = "";
    }
})

Server side code:

const http = require('http').createServer();

const io = require('socket.io')(http, {
    cors:{origin: "*" }
});

io.on('connection', (socket) => {
    console.log('a user connected');

    socket.on('message', (message) => {
        console.log(message);
        socket.broadcast.emit('message', `${message}`);
    });
});

http.listen(8080, () => console.log('listening on http://localhost:8080'));

CodePudding user response:

You need to write socket.on in the client side code like this

socket.on("message", function (messageFromOtherUser) {
  const divEl = document.createElement("div");
  divEl.className = "otherUser-message";
  messagesContainer.appendChild(divEl);
  const labelEl = document.createElement("label");
  labelEl.innerHTML = "otherUser";
  divEl.appendChild(labelEl);
  let messageSent = document.createElement("p");
  messageSent.innerHTML = messageFromOtherUser;
  divEl.appendChild(messageSent);
});
  • Related