【发布时间】:2016-10-18 15:02:38
【问题描述】:
我在我的 Angular 应用程序和我的服务器之间使用 socket.io 没有任何问题,但是在我的路由中使用 socket.io 时我不知道该怎么做。
这是我到目前为止所做的:
app.js
var server = app.listen(port);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
socket.on('server',function(data){
log.info(data.message);
});
socket.on('console',function(data){
log.info(data.message);
});
socket.emit('client',{action:"test"});
});
正如我所说,它有效。
现在我想在我的一条路由中使用 socket.io,路由从我的路由器加载:
require('./app/my.routes')(app,io);//i've tried to use it this way
my.routes.js
module.exports = function (app,io){
io = app.get('io');//and get it this way
io.sockets.emit('socket.io :: sucessfully passed from app to router')
log.info('Trying to load express routes...');
router.use(function (req, res, next) {
next(); // make sure we go to the next routes and don't stop here
});
require('./models.mongoose/user');
//require routes
var consoleRoute = require('./express.routes/console.route')
...
现在我有那个错误
io.sockets.emit('socket.io :: sucessfully passed from app to router')
^
TypeError: Cannot read property 'sockets' of undefined
我肯定做错了什么,但我不知道是什么。 有什么想法吗?
我也试过 app.set('io',io) 在 app.js 和 app.get('io') 在另一边,但它同样失败了
解决方案
终于找到解决办法了,
app.io = io.sockets.on('connection', function (socket) {
socket.on('server', function (data) {
log.info(data);
});
socket.emit('client', {
action: "alert",
text: 'test from socket io'
});
});;
现在它已链接到应用程序,我可以在任何地方使用它。
【问题讨论】:
标签: javascript angularjs node.js sockets