我最近将socket.io更新为最新版本0.9.8
上次我使用该应用时,我做了类似的事情:
io.sockets.emit("logged",this);
它有效。现在我明白了:
TypeError: Cannot call method 'emit' of undefined
at new Agent (/var/www/panel/models/agent.js:29:16)
at module.exports (/var/www/panel/modules/app.js:35:47)
at Query.Client.query (/var/www/panel/node_modules/mysql/lib/client.js:108:11)
at Query.EventEmitter.emit (events.js:85:17)
at Query._handlePacket (/var/www/panel/node_modules/mysql/lib/query.js:51:14)
at Client._handlePacket (/var/www/panel/node_modules/mysql/lib/client.js:319:14)
at Parser.EventEmitter.emit (events.js:88:17)
at Parser.write.emitPacket (/var/www/panel/node_modules/mysql/lib/parser.js:71:14)
at Parser.write (/var/www/panel/node_modules/mysql/lib/parser.js:576:7)
at Socket.EventEmitter.emit (events.js:88:17)
我认为这是因为有关范围或其他的事情,所以我只是这样做了:
// server.js
var express = require('express'),
server = express(),
Routes = require('./routes'),
App = require('./modules/app.js'),
database = require('./libraries/mysql.js'),
io = require('socket.io'),
mysql = require('mysql');
server.listen(8080);
io.listen(server);
io.sockets.emit('Hi there', {});
它只是不起作用,同样的错误,不同的行。
我做错了什么?
答案 0 :(得分:4)
您需要保存socketio.listen
的返回值并与之交互。我建议您按照socket.io上的示例进行操作。这样的事情可以解决问题:
var express = require('express'),
server = express(),
socketio = require('socket.io');
server.listen(8080);
var io = socketio.listen(server);
io.sockets.emit('Hi there', {});
甚至:
var express = require('express'),
server = express(),
io = require('socket.io').listen(server);
server.listen(8080);
io.sockets.emit('Hi there', {});