2016-06-16 52 views
3

我在我的angular應用和我的服務器之間使用socket.io時沒有任何問題,但是我不知道如何在我的路由中使用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.js app.set( 'IO',IO) 和 app.get( 'IO') 的另一邊,但它沒有都一樣

SOLUTION

最後,我已經找到了解決辦法,

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

現在,它鏈接到應用程序,我可以在任何地方使用它。

回答

5

您可以在您的快速配置文件中設置您的套接字io實現,並將「io」對象作爲應用程序中的變量傳遞。

app.io = io; 

的想法是做這樣的事情:

module.exports = function (app){ 
    app.io.sockets.emit('socket.io sucessfully passed from app to router'); 
} 
+0

你的意思是:app.io = 10我app.js然後變種X =需要(somefile)(應用程序,IO)所以我可以在像io.emit(....)這樣的文件中使用它? – antares667367

+1

只需通過應用程序,因爲它alteady將有io對象引用像require(「routes」)(app) –

+0

現在好了,沒有更多的錯誤,但它完全沉默,沒有任何反應。weird.I將繼續調查。 – antares667367