简体   繁体   中英

With SocketIO & node.js only the message I sent is not visible in chatroom

I developed the chat room app with node.js & expressjs in backend. Use socket.io with chat rooms.

And I found the when I send the message, outgoing messages are not shown. But it works well before so I research the github history but the codes are same as before.

And one thing I cannot understand is, ingoing messages functions are works well, only outgoing messages are not working.

But the DB part works well so When I refresh the page all the chat's are shown well.

The code shown below is part of my app.js's socketIO part.

[app.js]

const io = require('socket.io')(socket);

/* Socket IO Functions */
io.on('connection', function (socket) {
  // Join Room Scoket
  socket.on('JoinRoom', function (data) {
    socket.leave(`${data.leave}`)
    // console.log(`Leave ROOM : ${data.leave}`)
    socket.join(`${data.joinedRoomName}`);
    // console.log(`NEW JOIN IN ${data.joinedRoomName}`)
    // console.log(`RECEIVER : ${data.receiver}`)
    // When Reads the message SET notice to '1'
    // db.query(`UPDATE chatData SET notice='1' WHERE chatReceiver=? AND roomName=?`, [data.receiver, data.joinedRoomName])
    // console.log(data);
    Chat.aggregate([{
        $match: {
          'chatReceiver': data.receiver,
          'roomName': data.joinedRoomName,
          'chatNotice': 1
        }
      },
      {
        $set: {
          'chatNotice': 0
        }
      }
    ], (err, result) => {
      if (err) throw err;
      // console.log(result);
    })
  })

  // Send Message Socket
  socket.on('say', function (data) {

    //chat message to the others
    socket.to(`${data.joinedRoomName}`).emit('mySaying', data);
    console.log(data)
    console.log(`Message Send to : ${data.joinedRoomName}`)
    console.log(`Message Content : ${data.userId} : ${data.msg}`);
    // Chat Message Save to DB SQL

    Chat.create({
      'roomName': data.joinedRoomName,
      'chatSender': data.userId,
      'chatReceiver': data.receiver,
      'chatMessage': data.msg
    })
  });
}

[chat.js [Client Side]]

let socket = io();
/* SocketIO Functions */
$(function () {
    $('#message').focus(); // Init Focus to Input
    let fontColor = 'black';
    let nickName = '';
    let whoIsTyping = [];

    /* Submit Event (Keyboard Enter) */
    $('#chat').submit(function () {
        if (joinedRoomName === undefined) {
            /* Not yet joined Alert */
            const Toast = Swal.mixin({
                toast: true,
                position: 'bottom',
                showConfirmButton: false,
                timer: 5000,
                timerProgressBar: true,
                didOpen: (toast) => {
                    toast.addEventListener('mouseenter', Swal.stopTimer)
                    toast.addEventListener('mouseleave', Swal.resumeTimer)
                }
            })
            Toast.fire({
                icon: 'warning',
                title: 'Please joined room first!'
            })
            $('#message').val('Joined ROOM First!!');
        } else {
            if ($('#message') !== '') {
                let msg = $('#message').val();
                socket.emit('say', {
                    msg: msg,
                    userId: userId,
                    loginedId: userId,
                    receiver: others,
                    joinedRoomName: joinedRoomName
                });
            }
            // Say event means someone transmitted chat
            $('#message').val('');
            socket.emit('quitTyping')
        }
        return false;
    });

    /* Click Event (Click Send Button) */
    $('.msg_send_btn').click(function () {
        if (joinedRoomName === undefined) {
            $('#message').val('Joined ROOM First!!');
        } else {
            //submit only if it's not empty
            if ($('#message').val() != "") {
                let msg = $('#message').val();
                socket.emit('say', {
                    msg: msg,
                    userId: userId,
                    loginedId: userId,
                    receiver: others,
                    joinedRoomName: joinedRoomName
                });
            }
            // Say event means someone transmitted chat
            $('#message').val('');
            socket.emit('quitTyping')
        }
        return false;
    });

    /* Sending Messages Socket */  THIS PART IS CHAT PART!!!!
    socket.on('mySaying', function (data) {
        d = Date.now();
        d = new Date(d);
        d = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()} ${d.getHours() > 12 ? d.getHours() - 12 : d.getHours()} : ${d.getMinutes()} ${(d.getHours() >= 12 ? "PM" : "AM")}`;
        console.log(data.userId);
        console.log(userId);
        if (data.userId == userId) {
            $('.msg_history').append(`<div class="outgoing_msg"><div class="sent_msg"><p>${data.msg}</p><span class="time_date"> ${d}</span></div></div>`);
        } else {
            $('.msg_history').append(`<div class="incoming_msg"><div class="incoming_msg_img"><img src="${avatar_url}" alt="sunil"></div><div class="received_msg"><div class="received_withd_msg"><p>${data.msg}</p><span class="time_date">${d}</span></div></div></div>`);
            $('#chatData').text(`${data.msg}`)
        }
        Scroll();
    });

    /* Typing... Socket */
    socket.on('typing', function (whoIsTyping) {
        whoIsTyping = others;
        $('#message').attr('placeholder', `${whoIsTyping} is typing..`) // Typing... Message
    });

    /* End Typing Socket */
    socket.on('endTyping', function () {
        whoIsTyping = [];
        $('#message').attr('placeholder', "Type a Message"); // If Notyping Reset to Init placeholder
    })

    /* Input Typing Socket */
    $('#message').keyup(function (event) {
        if ($('#message').val() != "" && !whoIsTyping.includes(others)) {
            socket.emit('typing', {
                others,
                joinedRoomName
            });
        } else if ($('#message').val() == "" && whoIsTyping.includes(others)) {
            socket.emit('quitTyping', {
                others,
                joinedRoomName
            });
        }
    });
});

在此处输入图像描述

It looks like this. When I send chat to someone it send to other person works well but in my page, the chat that I sent is not shown.

I don't know where this bug come from.

In your app.js, you are using

socket.to("ROOM").emit('EVENT', data);

Which is, sending to all clients in "ROOM" room except sender

thus the sender will not receive the event (which is happening in your case). You want to include the sender in a broadcast event use following

io.in("ROOM").emit("EVENT", data);

and for your specific case

io.in(`${data.joinedRoomName}`).emit('mySaying', data);

look at Emit cheatsheet

First, thanks to answer above. And the codes are right.

In my client side socketio version is 2.X but the server side socketio is updated to 3.X so it's not wokring.

If I use version 2.X use my code, but use 3.0

io.in(`${data.joinedRoomName}`).emit('mySaying', data);

is the answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM