ant*_*367 3 javascript sockets node.js angularjs
我在我的角度应用程序和我的服务器之间使用socket.io没有任何麻烦,但我不知道如何在我的路由中使用socket.io.
这是我到目前为止所做的:
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"});
});
Run Code Online (Sandbox Code Playgroud)
正如我所说,它有效.
现在我想在我的一个路由中使用socket.io,从我的路由器加载的路由:
require('./app/my.routes')(app,io);//i've tried to use it this way
Run Code Online (Sandbox Code Playgroud)
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')
...
Run Code Online (Sandbox Code Playgroud)
现在我有这个错误
io.sockets.emit('socket.io :: sucessfully passed from app to router')
^
TypeError: Cannot read property 'sockets' of undefined
Run Code Online (Sandbox Code Playgroud)
我显然必须做错事但我不知道是什么.有任何想法吗 ?
我也试过app.js中的app.set('io',io)和另一边的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'
});
});;
Run Code Online (Sandbox Code Playgroud)
现在它与app相关联,我可以在任何地方使用它.
您可以在快速配置文件中设置套接字io实现,并将"io"对象作为变量传递到应用程序中.
app.io = io;
Run Code Online (Sandbox Code Playgroud)
我的想法是做这样的事情:
module.exports = function (app){
app.io.sockets.emit('socket.io sucessfully passed from app to router');
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3950 次 |
| 最近记录: |