Patrick DaVader
Patrick DaVader

Reputation: 2153

Socket.io + Express: Different events/functions for different routes

Well ... I got my first express + socketio node App up and running.

Socketio is used on almost every single page in my app because all the "lists" showed on those pages should be updated with server-push when new entries are added.

So I got my main app.js File + a routes dir with all the route.js files in it. Now I need different socketio events + functions for each route since different things happen on those pages.

Question now is how do I access my express server for initializing the socketio object?

// app.js
var server = app.listen(app.get('port'), function(){...});
var io = socketio.listen(server);
// socket.io code here
// the code from here on should be different for each route.js file

or in other words:

How can I exclude all my event and function definitions for socket.io into the corresponding route files so different socket.io events and functions are defined for each page? The socket can of course always run on the same port (I hope that's no problem?!).

I hope that was understandable ... a bit difficult to explain.

best regards Patrick

Upvotes: 3

Views: 1351

Answers (1)

Gntem
Gntem

Reputation: 7155

depending on the route that the user is connecting from you can use namespaces in socket.io library to emit a message to a specific group of users.

Emit a message to all users that where connected from /news

io.of('/news').emit('update',{message:"a new article is available"});

as for client side a simple event listener will do it (assuming user is of /news namespace)

socket.on('update',function(data){
 alert(data.message);
});

IMHO you do not need to different events, just use same events and handle them differently in each route.

Upvotes: 2

Related Questions