我正在使用SocketIO开发多个聊天室。而且似乎“加入会议室”功能运行良好,但离开会议室无法正常工作。
我使用三种不同的ID进行了测试,并测试了加入和离开功能
每个会议室链接的ID值都类似于<a href="#" onclick="joinChat()"><h5 id="Apple-cliffordfajardo">sangumee</h5></a>
[客户端代码]
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>`);
}
});
[服务器端代码]
// 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])
});
})
用户1与“ ROOM 1”聊天->可以! 用户2与“ ROOM 1”聊天->工作! 因此,用户1和用户2彼此聊天即可。
但是,如果用户2移至“ ROOM 2”,则应保留“ ROOM 1”,但似乎用户2仍与“ ROOM 1”连接。因此,用户2聊天的内容仍归ROOM 1
但是,如果用户1发送消息,则在用户2聊天页面中无法收到任何消息真的很奇怪。但是,如果用户3向用户2发送消息,则会收到消息,但无法发送给用户3。
我认为这是聊天逻辑问题
答案 0 :(得分:0)
实际上,这确实是一个简单的问题。我只是将joinedRoomName变量设置在外部并移动提交功能。
10-2-2019