Antonio Laguna
Antonio Laguna

Reputation: 9282

Socket.io out of scope or missing method?

I'm starting to play out with socket.io and I would really love to see a better written documentation because it's pretty hard to find which methods have every objects, how callbacks works and so on.

So I tried this with express and socket.io:

var app = require('express').createServer()
  , io = require('socket.io').listen(app);
app.listen(8080);
var clients = [];

/*Routes*/
app.get('/', function (req, res) {
    res.sendfile(__dirname + '/index.html');
});
app.get('/user/:id', function(req, res){
    io.sockets.broadcast.emit('user', {id: req.params.id});
});
io.sockets.on('connection', function (socket) {
    clients.push(socket.id);
    io.sockets.socket(socket.id).emit('connection', clients);
    socket.broadcast.emit('conexion', { id: socket.id });   
});

And when try to access: localhost:8080/user/test it doesn't work and outputs the following:

TypeError: Cannot call method 'emit' of undefined
    at /var/www/node/app.js:11:26
    at callbacks (/var/www/node/node_modules/express/lib/router/index.js:272:11)
    at param (/var/www/node/node_modules/express/lib/router/index.js:246:11)
    at param (/var/www/node/node_modules/express/lib/router/index.js:243:11)
    at pass (/var/www/node/node_modules/express/lib/router/index.js:253:5)
    at Router._dispatch (/var/www/node/node_modules/express/lib/router/index.js:280:4)
    at Object.handle (/var/www/node/node_modules/express/lib/router/index.js:45:10)
    at next (/var/www/node/node_modules/express/node_modules/connect/lib/http.js:203:15)
    at Object.handle (/var/www/node/node_modules/express/lib/http.js:84:5)
    at next (/var/www/node/node_modules/express/node_modules/connect/lib/http.js:203:15)

So, my guess is that the call is out of scope or the method doesn't exist or whatever. How could I solve this?

Upvotes: 1

Views: 1714

Answers (1)

alessioalex
alessioalex

Reputation: 63653

Use io.sockets.emit('user', {id: req.params.id}); instead of io.sockets.broadcast.emit.

Upvotes: 3

Related Questions