SocketIO离开会议室并加入新的会议室逻辑

时间:2019-02-22 07:51:23

标签: javascript node.js socket.io

我想知道我单击新房间后如何离开房间

我的页面是这样的。

enter image description here

左侧列表来自MySQL Server,它获取了我的聊天列表。每个房间名称都有ID值,即房间名称。它还具有onclick功能以在客户端使用该功能。

我想当我单击每个房间名称并运行joinChat()函数和运行joinChat()函数

时,
  1. 使用JoinRoom套接字
  2. 在服务器端运行socket.leave(`${data.joinedRoomName}`);
  3. 然后使用socket.join(`${data.joinedRoomName}`);代码加入新的Clicked Room

但是我不知道单击新房间时如何传递当前房间名称。因此,第2步出现了问题。

所以看起来像这样。

<a href="#" onclick="joinChat()">
<h5 id="sangumee-Quarterican-KJ">sangumee</h5>
</a>

[客户端代码]

var socket = io.connect('http://118.35.126.220:3001');
function joinChat() {
    let joinedRoomName = window.event.target.id;    // Get clicked id (ROOM NAME)
    $('.msg_history').empty();  // to Remove Previous Chats
    socket.emit('JoinRoom', {
        joinedRoomName: joinedRoomName
    });
    console.log(`Joined : ${joinedRoomName}`);
    $('#chat').on('submit', function (e) {  // Submit Event
        var msg = $('#message').val();  // Get entered Message
        e.preventDefault(); // Prevent reload the page
        if (!msg) return; // If no Message return
        $('#message').val('')   // To clean chat input
        socket.emit('send:message', {
            message: msg,
            userId: userId,
            loginedId: loginedId,
            joinedRoomName: joinedRoomName
        });
        // Draw to Outgoing side Chat (Send by me)
        $('.msg_history').append(`<div class="outgoing_msg"><div class="sent_msg"><p>${msg}</p><span class="time_date"> 11:01 AM    |    June 9</span></div></div>`);
    });
}

socket.on('receive:message', function (data) {
    console.log(`${data.userId} : ${userId}`)
    if (data.userId != userId) {
        // Draw to Incoming Side Chat (Send by another person)
        $('.msg_history').append(`<div class="incoming_msg"><div class="incoming_msg_img"><img src="https://ptetutorials.com/images/user-profile.png" alt="sunil"></div><div class="received_msg"><div class="received_withd_msg"><p>${data.message}</p><span class="time_date"> 11:01 AM    |    June 9</span></div></div></div>`);
    }
});

[服务器端代码]

/* MyPage User Chat Room */
router.get(`/:userId/admin/contact`, function (req, res, next) {
  let userId = req.params.userId;
  let loginedId = req.user.login;
  db.query(`SELECT * FROM chatRoom WHERE chatReceiver=? OR chatSender=?`, [userId, userId], function (error, room) {
    if (error) {
      throw `Error From /:userId/admin/contact ROUTER \n ERROR : ${error}`;
    }
    console.log(`Room : ${room}`);
    res.render('mypage/contact', {
      userId: userId,
      loginedId: loginedId,
      room: room
      // contactArray: contactArray
    })
  });
});

// Socket IO 
io.on('connection', function (socket) {
  // Join Room
  socket.on('JoinRoom', function (data) {
    socket.leave(`${data.joinedRoomName}`);
    console.log(`DATA : ${data.joinedRoomName}`)
    socket.join(`${data.joinedRoomName}`);
    console.log(`NEW JOIN IN ${data.joinedRoomName}`)
  })
  socket.on('send:message', function (data) {
    io.sockets.to(`${data.joinedRoomName}`).emit('receive:message', data);
    console.log(`Message Send to : ${data.joinedRoomName}`)
    console.log(`Message Content : ${data.userId} : ${data.message}`);
    // Save Message In DB
    db.query(`INSERT INTO chatData (roomName, chatSender, chatMessage) VALUES (?,?,?)`,[data.joinedRoomName, data.userId, data.message])
  });
});

1 个答案:

答案 0 :(得分:2)

当套接字尝试加入另一个房间时,您可以取消其他所有房间的连接:

 Object.keys(socket.room)
  .filter(it => it !== socket.id)
  .forEach(id => socket.leave(id));

或者您只需在客户端(或服务器)上保留一个变量:

 let current;

然后,如果您加入,请将其发送到服务器并刷新:

socket.emit('JoinRoom', {
    joinedRoomName,
    leave: current,
});

current = joinedRoomName;