Socket.io'on'返回undefined

时间:2013-08-09 22:19:45

标签: node.js socket.io

好的,所以我正在尝试学习socket.io,我收到了这个错误:

  

io.socket.on('connection',function(socket)   TypeError:无法调用未定义的方法'on'

继承我的代码:

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);
    });
});

我知道它会变得相当明显。

2 个答案:

答案 0 :(得分:5)

应该是io.sockets.on(“套接字”而不是“套接字”):

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

答案 1 :(得分:0)

我认为此代码已不再有效。 以下是我处理socket.io和http服务器的事情。

var app = require('http'),
    io = require('socket.io');

var handler = function(req, res) { /* your handler function*/ };
var server = app.createServer(handler).listen( 8000 );
var ios = io.listen(server);

ios.sockets.on('connection', function(socket){
   socket.emit('message', {'message': 'hello world'});
});