socket.io监听/监听事件

我很惊讶的看着socket.io文档,当它绑定到一个端口没有被socket.io触发的事件…我正在寻找一个“听”/“聆听”事件…

http://socket.io/docs/server-api/

我有一个用http.Server实例初始化的简单模块:

 var io = require('socket.io'); var socketServer = null; function getSocketServer(httpServer) { if (socketServer === null) { if (httpServer == null) { throw new Error('need to init socketServer with http.Server instance'); } socketServer = io.listen(httpServer); } return socketServer; } module.exports = { getSocketServer:getSocketServer }; 

当我需要这个模块时,我想倾听一个“倾听”事件。

就像是:

 var socket = require('./socket-cnx').getSocketServer(); socket.on('listening',function(err){ }); 

我想主要的原因是因为on API被用于事件名称。

所以socket.io本身不听。 http服务器监听,这是将发出listening事件的对象。

如果您允许socket.io为您创buildhttp服务器实例,那么该实例将作为您的io实例的httpServer属性发布,因此您应该可以执行io.httpServer.on('listening', myOnListeningHandler)

这是一个工作示例程序:

 var io = require('socket.io')(4001) io.httpServer.on('listening', function () { console.log('listening on port', io.httpServer.address().port) })