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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With