我很惊讶地看着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)
我想主要原因是因为on
API 用于事件名称。
所以 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)
归档时间: |
|
查看次数: |
5729 次 |
最近记录: |