Node.js - Socket.io - Express 3

I am a noob for Node.js and Express :( I had a problem accessing the socket.io object in other modules. I created a global variable to store the socket object, but as soon as the user closes the connection, the connection is no longer available. Technically, I assume that the connection is still ongoing, but I am deleting it for resource reasons.

Please note that each time you connect, note that this socket is assigned to a global variable that is available for all other modules.

// App.js var io = require('socket.io').listen(server); var sessionsConnections = {}; io.sockets.on('connection', function (socket) { global.socket = socket; sessionsConnections[socket.id] = socket; ..... } socket.on("disconnect", function() { delete sessionsConnections[socket.id]; }); // Match.js global.socket.emit('lobby:createMatch', data); 

If the last connection assigned to the global closure of Match.js will be twisted. At this point, Match.js is the only module that will ever need this socket.io link. Match.js has a bunch of exports for handling events, emitting changes, and rendering visualizations.

Are there any suggestions as to how this is handled? Is it possible to create an instance of the original socket connection to work in App.js in order to get a global link?

+4
source share
2 answers

The socket variable in io.sockets.on('connection', function(socket) {...}) is different for each connection.

Since your global.socket code always has a link to a socket relative to the last connected client, it is normal if this client disconnects, this socket will die.

In any case, I see no reason to use a global variable. If you need to send a message to a specific client, you can use the socket variable in the connection callback:

 io.sockets.on('connection', function (socket) { socket.emit('foo', 'bar'); } 

If you need to access sockets in another module, you can export the sessionsConnections object and access the socket that you need by its identifier:

 //In app.js exports.connections = sessionsConnections; //In match.js var app = require('./app.js'); app.connections[clientId].emit('foo', 'bar'); 

Of course you need to track the id somewhere.

+4
source

You can try express.io ,

http://express-io.org/

 npm install express.io 

It works just like express, except that it has built-in socket.io integration. It also has basic routing, so it’s a little easier for you to deal with your problem.

Take a look at this simple example:

 app = require('express.io')() app.http().io() app.io.route('some-event', function(req) { req.io.broadcast('announce', 'someone triggered some-event') }) app.listen(7076) 

You can also route with objects, which makes it more like a traditional controller:

 app = require('express.io')() app.http().io() app.io.route('posts', { create: function(req) { // create a post }, remove: function(req) { // remove a post } }) app.listen(7076) 

Hope this helps!

0
source

All Articles