Home > front end >  Chat App with Socket.Io - Difference between sending and receiving a message
Chat App with Socket.Io - Difference between sending and receiving a message

Time:12-16

I'm trying to create a little chat app for a school project, but I encountered a little problem since I'm really new to socket.io // node.js (coding in general). English is not my first language so I'm finding it hard to actually understand how it works exactly from tutorials. Right now I have 2 css classes, one for the sent messages and one for the received messages. How do I make it so the classes will apply the right way for each message? How do I check which message is sent by me, and which is received from another user? It's really unclear for me.

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);
        io.emit('message', `${message}`);
    });
});


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

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');

socket.on('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);
})

sendBtn.addEventListener('click', () =>{
    if(messageInput.value === ""){
        return;
    } else {
        const text = messageInput.value;
        socket.emit('message', text);
        messageInput.value = "";
    }
})

CodePudding user response:

From what I understand you are not creating any element when you are sending any text. Instead you are emitting the same message to everyone :

io.emit('message', `${message}`);

and in that way you are thinking that you are actually creating HTML divs for both sending and receiving. Firstly your server code should be :

socket.broadcast.emit('message', `${message}`);

(This sends to everyone but the sender and should work for your simple case with 2 users. Later you will need rooms)

This will show that you were actually not creating any elements while sending messages.

socket.on('message', text => {
})

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 = "";
    }
})

Replace the above with your classname and labels

CodePudding user response:

Why do you have two classes for sending and receiving messages? socket.emit will emit the message to all clients, and then you can append the message.

As seen from the socket.io chat tutorial (socket.io emit

Secondly, if you want to check which users are which, you can assign a socket.id to users, like so.

io.on('connection', function(socket) {
  console.log(`A user connected. ID: ${socket.id}`)
  socket.on('disconnect', function() {
    console.log(`A user disconnected. ID: ${socket.id}`);
  });
});

This way, each user has a unique socket id. Maybe this can help you? I'm a bit unsure on what your're asking.

  • Related