Warm tip: This article is reproduced from serverfault.com, please click

javascript-使用SocketIO和node.js时,只有我发送的消息在聊天室中不可见

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

发布于 2020-11-30 13:55:20

我在后端使用node.js和expressjs开发了聊天室应用程序。在聊天室中使用socket.io。

我发现当我发送消息时,未显示传出消息。但是它在之前运行良好,因此我研究了github历史,但是代码与以前相同。

我无法理解的一件事是,传入消息功能运行良好,只有传出消息无效。

但是数据库部分的效果很好,因此当我刷新页面时,所有聊天记录都可以很好地显示。

下面显示的代码是我的app.js的socketIO部分的一部分。

[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 [客户端]]

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

在此处输入图片说明

看起来像这样。当我将聊天发送给某人时,它发送给其他人的效果很好,但在我的页面中,未显示我发送的聊天。

我不知道这个错误来自哪里。

Questioner
writingdeveloper
Viewed
0
21.1k 2020-11-30 23:17:26

在你的app.js中,你正在使用

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

也就是说,发送给“ ROOM”房间中的所有客户端(发件人除外)

因此,发件人将不会收到事件(你的情况正在发生)。你想在以下广播事件中使用发送者

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

并针对你的具体情况

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

看看发射备忘单