我很惊讶地看到 socket.io
文档,当它绑定(bind)到端口时,socket.io 没有触发任何事件...我正在寻找“listen”/“listening”事件...
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 为您创建 http 服务器实例,则该实例将发布为 httpServer property of your io instance所以你应该能够做 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)
})
关于node.js - socket.io 监听/监听事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34914425/