【问题标题】:Export the same websocket connection to different files将相同的 websocket 连接导出到不同的文件
【发布时间】:2022-01-29 06:34:46
【问题描述】:

为了澄清,我设置了一个 websocket,每隔几分钟就会发回一些数据,并且根据发回的数据,我想对这些数据运行一些例程。而且我想在一天中的不同时间使用相同的 websocket 继续运行不同的例程。我需要流数据,但我还需要一个事件监听器。我的想法是在不同的文件中启动 websocket,然后将其导出到文件夹中的不同文件,但这不起作用,因为新的 websocket 启动了。我一次只能有 1 个 websocket 连接。

例如:

openConnection.js

(() =>
{
    const url = "wss://stream.data";
    const ws = new WebSocket(url);

    ws.on('open', () =>
    {
        ws.send(`{"authorize"}`);
    });

    module.exports = ws;

})();

然后 ->

someFunction.js

const ws = require('./openConnection.js');

function foo ()
{
    // using the imported websocket
    ws.addEventListener('message', (data) =>
    {
        doSomething(data)
    });
}

有没有办法让我在不同的文件中使用相同的 websocket 连接?

【问题讨论】:

  • 你也在用快递吗?
  • 仅供参考,在您的模块中使用 IIFE 的理由为零。该模块已经是它自己的函数范围,因此在该函数范围内使用 IIFE 没有任何作用。而且,您正在展示 CommonJS 模块与 ESM 模块的混合。选择 importexportrequire()module.exports。不要混音,除非您想深入了解如何成功混音的复杂世界。

标签: node.js websocket server


【解决方案1】:

我不知道这是否对你有帮助,但在使用 socket.io 和 express 时,你可以简单地将 io 服务器传递给本地人

这里是例子

const server = http.createServer(app);
// Create HTTP server
const io = new Server(server, {
  cors: {
    origin: '*',
  },
}); // Create Socket.io server

app.locals.io = io; // Set io to global

在其他文件中

const { io } = req.app.locals;

io.on('connection', (socket) => {
    console.log('New client connected');
    socket.on('disconnect', () => {
      console.log('Client disconnected');
    });
  });

【讨论】:

    【解决方案2】:

    将 CommonJS 模块与 module.exportsrequire() 一起使用:

    const url = "wss://stream.data";
    const ws = new WebSocket(url);
    
    ws.on('open', () =>
    {
        ws.send(`{"authorize"}`);
    });
    
    module.exports.ws = ws;
    

    并且,将其导入 CommonJS 模块:

    const { ws } = require('./openConnection.js');
    
    function foo ()
    {
        // using the imported websocket
        ws.addEventListener('message', (data) =>
        {
            doSomething(data)
        });
    }
    

    而且,您可以在任何其他文件中使用相同的 const { ws } = require('./openConnection.js');,因为模块句柄被缓存,因此您在第二次、第三次、第四次 require() 时,它们只会返回前一个 module.exports 对象。

    如果你不尝试混合 CommonJS 模块和 ESM 模块,生活会更简单。因此,module.exports 在 CommonJS 模块中与 require() 一起使用,import 在 ESM 模块中与 export 一起使用。

    有多种方法可以从另一种类型的模块中加载,但是一旦您尝试这样做,生活就会变得更加复杂,因此最好尽可能坚持使用一种模块类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 2015-08-10
      • 2019-09-15
      • 2018-10-14
      • 2018-10-09
      • 2014-06-16
      相关资源
      最近更新 更多