I'm developing multiple Chatting room with SocketIO. And It seems that Join to the Room function is working well but leaving the room is not working.
I tested with three different ID and join and leave function test
Each Room link has id value like <a href="#" onclick="joinChat()"><h5 id="Apple-cliffordfajardo">sangumee</h5></a>
[Client Side Code]
var socket = io.connect('IPADDRESS');
let current;
function joinChat() {
let joinedRoomName = window.event.target.id; // Get clicked id (ROOM NAME)
$('.msg_history').empty(); // to Remove Previous Chats
socket.emit('JoinRoom', {
joinedRoomName,
leave: current,
});
current = joinedRoomName;
console.log(`CURRENT ROOM : ${current}`);
console.log(`NewJoined ROOM ${joinedRoomName}`)
$('#chat').submit(function () {
//submit only if it's not empty
if ($('#message').val() != "") {
var msg = $('#message').val();
socket.emit('say', {
msg: msg,
userId: userId,
loginedId: loginedId,
joinedRoomName: joinedRoomName
});
//say event means someone transmitted chat
$('#message').val('');
}
return false;
});
}
$(function () {
socket.on('mySaying', function (data) {
if (data.userId != userId) {
$('.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.msg}</p><span class="time_date"> 11:01 AM | June 9</span></div></div></div>`);
} else {
$('.msg_history').append(`<div class="outgoing_msg"><div class="sent_msg"><p>${data.msg}</p><span class="time_date"> 11:01 AM | June 9</span></div></div>`);
}
});
[Server Side Code]
// Socket IO
io.on('connection', function (socket) {
// Join Room
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}`)
})
// Send Message
socket.on('say', function (data) {
console.log(`${data.userId} : ${data.msg}`);
//chat message to the others
//mySaying to the speaker
io.sockets.to(`${data.joinedRoomName}`).emit('mySaying', data);
console.log(`Message Send to : ${data.joinedRoomName}`)
// console.log(`Message Content : ${data.userId} : ${data.message}`);
db.query(`INSERT INTO chatData (roomName, chatSender, chatMessage) VALUES (?,?,?)`, [data.joinedRoomName, data.userId, data.msg])
});
})
User 1 Chat to 'ROOM 1' -> Works! User 2 Chat to 'ROOM 1' -> Works! So User 1 & User 2 Chat each other works.
But If User 2 move to 'ROOM 2', 'ROOM 1' should be leaved but It seems that User 2 still connect with 'ROOM 1'. So User 2 chat something it still goes to ROOM 1
However, it is really strange that If User 1 send message, In User 2 chat page cannot get any message. But if User 3 send message to User 2 get message but cannot send to User 3.
I think it's chat logic problem