0

I've a web socket application and using socketIO to send a message to the server to interact with a second page.

Page 1 sends a message to the server, the server tells page 2 to do something. This works well, and because I have many different pages doing this I am using the 'rooms' function of SocketIO:

Page 1

function tryClose(shortCode) { //shortCode is the room name
  console.log('Trying to close ' + shortCode)
  socket.emit('closePlease', shortCode);
}

========================================================================== Server

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

========================================================================== Page 2

socket.on('closePlease', function () {
  console.log ('Remote request to close session received!')
  //close the modal and display main menu.
  
  socket.emit('leaveRoom', shortCode)

});

My issue starts where the leaveRoom msg isn't returned to the server if the user has lost connection to the server or the webpage was already closed without firing the 'leaveRoom' msg. This is possible if the network is dropped and the browser closed, and will result in a number of objects and arrays being left open within my NodeJS app. The 'leaveRoom' process is designed to take care of these.

How can I modify the server function so that if the 'closePlease' message is unable to be delivered to the page, the 'leaveRoom' function is executed on the server?

I did look in to callbacks but hit an error message about being unable to use callbacks when broadcasting in a room.

I'm using SocketIO version: "^2.3.0",

TheMiddle
  • 93
  • 8
  • what you are trying to do here exactly ? do you want just to send messages between pages? – azdeviz Jul 14 '20 at 11:01
  • I am trying to have the server detect when the message cannot be delivered, following an emit, in a room – TheMiddle Jul 14 '20 at 11:17
  • use try catch or throw an other thing when it can't be in case of error or something happen on the server – azdeviz Jul 14 '20 at 11:45
  • I will check that but I don't think there will be an error... SocketIO will just be shouting the message in an empty room and there won't be a connection listening! – TheMiddle Jul 14 '20 at 11:55

1 Answers1

0

Ended up with the following. The key lied in the answer here: linky

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];

    }
TheMiddle
  • 93
  • 8