【问题标题】:Socket.io out of scope or missing method?Socket.io 超出范围或缺少方法?
【发布时间】:2011-12-26 21:20:08
【问题描述】:

我开始使用 socket.io,我真的很想看到更好的书面文档,因为很难找到每个对象都有哪些方法,回调如何工作等等。

所以我用 express 和 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 });   
});

当尝试访问时: localhost:8080/user/test 它不起作用并输出以下内容:

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)

所以,我的猜测是调用超出范围或方法不存在或其他原因。我该如何解决这个问题?

【问题讨论】:

  • 试试io.sockets.emit('user', {id: req.params.id}); 而不是io.sockets.broadcast.emit
  • 它有效@alessioalex :)
  • 我已将我的评论添加为答案,因此您可以投票并接受它。 (这样问题就不会显示为未回答)
  • broadcast.emit 不幸的是不存在。仅广播。发送。

标签: node.js express socket.io


【解决方案1】:

使用io.sockets.emit('user', {id: req.params.id}); 代替io.sockets.broadcast.emit

【讨论】:

    猜你喜欢
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多