Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js & Socket.IO - Rooms issue

Considering a multi-chat application. Users can join multiple rooms ( socket.join(room) ), users can leave a room ( socket.leave(room) ).

When socket is leaving a room I notify the other room participants. If the socket is currently in 3 rooms, and he suddenly disconnects from the website without leaving the rooms the proper way, how can I notify those rooms that the user has left ?

If I work with the on socket disconnect event, the user will no longer be in any room at that point. Is the only way keeping a separate array of users, or is there some clever way I haven't thought about?

like image 415
Gabriel Gray Avatar asked Dec 21 '12 03:12

Gabriel Gray


People also ask

What is NodeJS used for?

It is used for server-side programming, and primarily deployed for non-blocking, event-driven servers, such as traditional web sites and back-end API services, but was originally designed with real-time, push-based architectures in mind. Every browser has its own version of a JS engine, and node.

Is NodeJS better than Python?

js vs Python, Node. js is faster due to JavaScript, whereas Python is very slow compared to compiled languages. Node. js is suitable for cross-platform applications, whereas Python is majorly used for web and desktop applications.

Is NodeJS frontend or backend?

Node. js is sometimes misunderstood by developers as a backend framework that is exclusively used to construct servers. This is not the case; Node. js can be used on the frontend as well as the backend.

Is NodeJS a programming language?

Node. js is best defined as a JavaScript runtime that works on the famous and ultra-powerful V8 engine by JavaScript. In simpler terms, Node. js can be defined as a programming language that works well as a development runtime.


1 Answers

During the disconnect event the socket is still available to your process. For example, this should work

io.socket.on('connection', function(socket){
    socket.on('disconnect', function() {
       // this returns a list of all rooms this user is in
       var rooms = io.sockets.manager.roomClients[socket.id];
       for(var room in rooms) {
           socket.leave(room);
       }
    });
});

Although this is not actually necessary as socket.io will automatically prune rooms upon a disconnect event. However this method could be used if you were looking to perform a specific action.

like image 84
Loourr Avatar answered Sep 25 '22 18:09

Loourr