2013-07-27 24 views
3

這是我的應用程序配置如何從路由文件中發出socket.io中的事件?

app.js

//SERVER 
var server = app.listen(3000, function(){ 
    console.log("Express server listening on port %d in %s mode", app.get('port'), 
    app.settings.env); 
}); 
//SOCKET.IO 
var io = require('./socket.io').listen(server) 

/socketio

var socketio = require('socket.io') 

module.exports.listen = function(app) 
{ 
    io = socketio.listen(app); 
    io.configure('development',function() 
    { 
      //io.set('transports', ['websocket', 'xhr-polling']); 
      //io.enable('log'); 
    }); 
    io.configure('production',function() 
    { 
     io.enable('browser client minification'); // send minified client 
     io.enable('browser client etag');   // apply etag caching logic based on version number 
     io.set('log level', 1);     // reduce logging 
     io.set('transports', [      // enable all transports (optional if you want flashsocket) 
      'websocket' 
      , 'flashsocket' 
      , 'htmlfile' 
      , 'xhr-polling' 
      , 'jsonp-polling' 
     ]); 
    }); 
    io.sockets.on('connection', function (socket) 
    { 
     console.log("new connection: "+socket.id); 
     socket.on('disconnect',function(){console.log("device "+socket.id+" disconnected");}); 

     socket.emit('news', { hello: 'world' }); 
     socket.on('reloadAccounts',function(data) 
     { 
      var accounts=['account1','account2'] 
      socket.emit('news',accounts) 
     }); 
    }); 
    return io 
} 

/路線

exports.newAccount=function(fields,callback)//localhost:3000/newAccountForm 
    { 
//... bla bla bla config db connection bla bla bla 
      db.collection('accounts').insert(fields,function(err,result) 
      { 
       if(err) 
       { 
        console.warn(err); 
        db.close(); 
        return callback(err,null); 
       }else{ 
        if(result) 
        { 
         db.close(); 
         return callback(null,result); 
           socket.emit('new account created',result) // i want to emit a new event when any user create an account 

        }else{ 
         db.close(); 
         return callback('no se consigue resultado',null); 
        } 
       } 
      }) 
     }); 
    } 

如何socket.io從發出事件路線文件?

+0

[在快速路由文件中使用socket.io]的可能重複(http://stackoverflow.com/questions/18856190/use-socket-io-inside-a-express-routes-file) – GiveMeAllYourCats

回答

1

首先,您需要確定要發送新信息的套接字。如果是全部(連接到您的應用的所有人),這很容易,只需使用io.sockets.emit:

./socket.io文件中,您在io = socketio.listen(app);之後的某個位置添加exports.sockets = io.sockets;。然後在routes文件,你可以發出這樣的:

var socketio = require('./socket.io'); 
socketio.sockets.emit('new account created', result); 

如果您知道您要發送到插座ID,那麼你可以這樣做:

var socketio = require('./socket.io'); 
socketio.sockets.sockets[socketId].emit('new account created', result); 

您也可以選擇插座用快遞會話ID:

首先,你需要會話ID連接到插座上的授權:

io.set('authorization', function (data, accept) { 
    // check if there's a cookie header 
    if (data.headers.cookie) { 
     // if there is, parse the cookie 
     data.cookie = cookie.parse(data.headers.cookie); 
     // note that you will need to use the same key to grad the 
     // session id, as you specified in the Express setup. 
     data.sessionID = data.cookie['express.sid']; 
    } else { 
     // if there isn't, turn down the connection with a message 
     // and leave the function. 
     return accept('No cookie transmitted.', false); 
    } 
    // accept the incoming connection 
    accept(null, true); 
}); 

然後你就可以與會話ID選擇插座:

var socketio = require('./socket.io'); 
var sockets = socketio.sockets.forEach(function (socket) { 
    if (socket.handshake.sessionID === req.sesssionID) 
     socket.emit('new account created', result); 
}); 

您還可以查詢會話存儲和使用我上述的方法,發射具有的sessionId符合您查詢到插座的事件。