socket.io 监听/监听事件

Ale*_*lls 1 node.js 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
};
Run Code Online (Sandbox Code Playgroud)

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

就像是:

var socket = require('./socket-cnx').getSocketServer();

socket.on('listening',function(err){

});
Run Code Online (Sandbox Code Playgroud)

我想主要原因是因为onAPI 用于事件名称。

Pet*_*ons 5

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

如果您允许 socket.io 为您创建 http 服务器实例,则该实例将发布为您的 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)
})
Run Code Online (Sandbox Code Playgroud)