我有一个web套接字应用程序,并使用socketIO向服务器发送消息以与第二个页面交互。
页面1向服务器发送消息,服务器告诉页面2做点什么。这很好,因为我有很多不同的页面在做这件事,所以我使用SocketIO:的"房间"功能
第1页
function tryClose(shortCode) { //shortCode is the room name
console.log('Trying to close ' + shortCode)
socket.emit('closePlease', shortCode);
}
==========================================================================服务器
socket.on('closePlease', function (data) {
//Send a request to any open sessions with an active browser to close the session
io.sockets.in(data).emit('closePlease');
});
==========================================================================第2页
socket.on('closePlease', function () {
console.log ('Remote request to close session received!')
//close the modal and display main menu.
socket.emit('leaveRoom', shortCode)
});
我的问题开始于,如果用户失去了与服务器的连接,或者网页已经关闭而没有触发"leaveeRoom"消息,则leaveRoom
消息不会返回到服务器。如果网络被断开,浏览器关闭,这是可能的,这将导致我的NodeJS应用程序中的许多对象和数组处于打开状态。"离开eRoom"流程旨在处理这些问题。
如何修改服务器功能,以便在"closePlease"消息无法传递到页面时,在服务器上执行"leaveeRoom"功能?
我确实查看了回调,但发现了一条错误消息,说在房间里广播时无法使用回调。
我正在使用SocketIO版本:"^2.3.0";,
最终得到以下结果。关键在于这里的答案:链接
io.in(data).clients((err , clients) => {
logger.warn('There are ' + clients.length + ' connections in session: ' + data);
if (clients.length > 0) {
io.sockets.in(data).emit('closeOrder', data);
}else {
//No connections to this session, remove from the server
logger.info(_.at(activeRooms[data], 'orgTitle') +' forcefully terminated ' + data + ' due to having no existing session connections');
delete activeRooms[data];
}