我开始玩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)
所以,我的猜测是呼叫超出范围或方法不存在或其他什么。我怎么能解决这个问题?
答案 0 :(得分:3)
使用io.sockets.emit('user', {id: req.params.id});
代替io.sockets.broadcast.emit
。