Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io 'on' is returning undefined

Ok, so I'm trying to learn socket.io and I get this error:

io.socket.on('connection', function (socket) TypeError: Cannot call method 'on' of undefined

heres my code:

var express = require('express')
  , app = express.createServer()
  , routes = require('./routes')
  , user = require('./routes/user')
  , path = require('path')
  , io = require('socket.io').listen(app);


// all environments
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

app.listen(3000);

app.get('/', routes.index);
app.get('/users', user.list);

io.socket.on('connection', function (socket) {
    socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
        console.log(data);
    });
});

I know its going to be something rather obvious.

like image 231
JDillon522 Avatar asked Aug 09 '13 22:08

JDillon522


1 Answers

Should be io.sockets.on ("sockets" instead of "socket"):

io.sockets.on('connection', function (socket) {
    socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
        console.log(data);
    });
});
like image 70
go-oleg Avatar answered Sep 18 '22 22:09

go-oleg