栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何将socket.io导出到Node.js中的其他模块中?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将socket.io导出到Node.js中的其他模块中?

由于app.js通常是应用程序中的主要初始化模块,因此通常会同时初始化Web服务器和socket.io并加载应用程序所需的其他内容。

因此,

io
与其他模块共享的一种典型方法是将它们传递给该模块的构造函数中的其他模块。那会像这样工作:

var server = require('http').createServer(app);var io = require('socket.io')(server);// load consumer.js and pass it the socket.io objectrequire('./consumer.js)(io);// other app.js pre follows

然后,在consumer.js中:

// define constructor function that gets `io` send to itmodule.exports = function(io) {    io.on('connection', function(socket) {        socket.on('message', function(message) { logger.log('info',message.value); socket.emit('ditConsumer',message.value); console.log('from console',message.value);        });    });};

或者,如果您想使用一种

.start()
方法来初始化事物,则可以对此进行相同的操作(存在细微差别):

// app.jsvar server = require('http').createServer(app);var io = require('socket.io')(server);// load consumer.js and pass it the socket.io objectvar consumer = require('./consumer.js);consumer.start(io);// other app.js pre follows

而Consumer.js中的start方法

// consumer.js// define start method that gets `io` send to itmodule.exports = {    start: function(io) {        io.on('connection', function(socket) { socket.on('message', function(message) {     logger.log('info',message.value);     socket.emit('ditConsumer',message.value);     console.log('from console',message.value); });        });    };}

这就是所谓的资源共享“推送”模块。正在加载的模块通过在构造函数中传递一些共享信息给您。

还有“拉”模型,其中模块本身调用其他模块中的方法来检索共享信息(在这种情况下为

io
对象)。

通常,可以使任何一个模型都可以工作,但是鉴于模块的加载方式以及谁拥有所需的信息以及您打算如何在其他情况下重用模块,通常一个或另一个模型会更自然。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/417912.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号