如何导出插座。io到nodejs中的其他模块?

时间:2022-08-22 16:32:37

I have socket.io working in app.js but when i am trying to call it from other modules its not creating io.connection not sure ?

我有套接字。io在app.js中工作,但是当我试图从其他模块调用它时,它并没有创建io。连接不确定?

app.js

app.js

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var ditconsumer = require('./app/consumers/ditconsumer');
ditconsumer.start(io);
server.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});

consumer.js

consumer.js

module.exports = {
    start: function (io) {
        consumer.on('message', function (message) {
            logger.log('info', message.value);
            io.on('connection', function (socket) {
                socket.on('message', function(message) {
                    socket.emit('ditConsumer',message.value);
                    console.log('from console',message.value);
                });
            });
        });
}
}

3 个解决方案

#1


17  

Since app.js is usually kind of the main initialization module in your app, it will typically both initialize the web server and socket.io and will load other things that are needed by the app.

由于app.js通常是应用程序的主要初始化模块,它通常同时初始化web服务器和套接字。io并将加载应用程序需要的其他东西。

As such a typical way to share io with other modules is by passing them to the other modules in that module's constructor function. That would work like this:

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

var server = require('http').createServer(app);
var io = require('socket.io')(server);

// load consumer.js and pass it the socket.io object
require('./consumer.js)(io);

// other app.js code follows

Then, in consumer.js:

然后,在consumer.js:

// define constructor function that gets `io` send to it
module.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);
        });
    });
};

Or, if you want to use a .start() method to initialize things, you can do the same thing with that (minor differences):

或者,如果您想使用.start()方法初始化东西,您可以对它做同样的事情(细微的区别):

// app.js
var server = require('http').createServer(app);
var io = require('socket.io')(server);

// load consumer.js and pass it the socket.io object
var consumer = require('./consumer.js);
consumer.start(io);

// other app.js code follows

And the start method in consumer.js

以及consumer.js中的start方法

// consumer.js
// define start method that gets `io` send to it
module.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);
            });
        });
    };
}

This is what is known as the "push" module of resource sharing. The module that is loading you pushes some shared info to you by passing it in the constructor.

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

There are also "pull" models where the module itself calls a method in some other module to retrieve the shared info (in this case the io object).

还有“拉”模型,其中模块本身调用其他模块中的方法来检索共享信息(在本例中是io对象)。

Often, either model can be made to work, but usually one or the other will feel more natural given how modules are being loaded and who has the desired information and how you intend for modules to be reused in other circumstances.

通常,任何一个模型都可以用来工作,但是考虑到模块是如何加载的、谁拥有所需的信息以及您打算如何在其他情况下重用模块,通常一个模型或另一个模型会感觉更自然。

#2


12  

If you want to avoid the global scope, make your io exist in a separate file like this:

如果您希望避免全局作用域,请将您的io保存在如下所示的单独文件中:

var sio = require('socket.io');
var io = null;

exports.io = function () {
  return io;
};

exports.initialize = function(server) {
  io = sio(server);

  io.on('connection', function(socket) {
    // Producer.startProducer();
    /*ditconsumer.start(function(value){
        io.emit('ditConsumer',value);
    });*/
    socket.on('createlogfile', function() {
      logsRecording.userLogs(function(filename) {
        socket.emit('filename', filename);
      });

    });
    socket.on('startrecording', function(filename) {
      console.log('response after creating file', filename);
      logsRecording.recordLogs(filename);
      //value that will be send it to file
    });
  });
};

Then in app.js:

然后在app.js:

var server = require('http').createServer(app);
var io = require('./io').initialize(server);

server.listen(...);

and in consumer.js:

而在consumer.js:

...
var socket = require('../io').io();
...

#3


0  

You can make a singleton instance in just 4 lines.

您可以在仅仅4行中创建一个单例实例。

In websocket.js write your server configuration code.

websocket。编写服务器配置代码。

const socketIO = require('socket.io');
const server = require('http').createServer();
server.listen(8000);

module.exports = socketIO(server);

Then in your consumer.js just require the file

然后在你的消费者。js只需要文件

const socket = require('./websocket');

/* API logic here */

socket.emit('userRegistered', `${user.name} has registered.`);

#1


17  

Since app.js is usually kind of the main initialization module in your app, it will typically both initialize the web server and socket.io and will load other things that are needed by the app.

由于app.js通常是应用程序的主要初始化模块,它通常同时初始化web服务器和套接字。io并将加载应用程序需要的其他东西。

As such a typical way to share io with other modules is by passing them to the other modules in that module's constructor function. That would work like this:

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

var server = require('http').createServer(app);
var io = require('socket.io')(server);

// load consumer.js and pass it the socket.io object
require('./consumer.js)(io);

// other app.js code follows

Then, in consumer.js:

然后,在consumer.js:

// define constructor function that gets `io` send to it
module.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);
        });
    });
};

Or, if you want to use a .start() method to initialize things, you can do the same thing with that (minor differences):

或者,如果您想使用.start()方法初始化东西,您可以对它做同样的事情(细微的区别):

// app.js
var server = require('http').createServer(app);
var io = require('socket.io')(server);

// load consumer.js and pass it the socket.io object
var consumer = require('./consumer.js);
consumer.start(io);

// other app.js code follows

And the start method in consumer.js

以及consumer.js中的start方法

// consumer.js
// define start method that gets `io` send to it
module.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);
            });
        });
    };
}

This is what is known as the "push" module of resource sharing. The module that is loading you pushes some shared info to you by passing it in the constructor.

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

There are also "pull" models where the module itself calls a method in some other module to retrieve the shared info (in this case the io object).

还有“拉”模型,其中模块本身调用其他模块中的方法来检索共享信息(在本例中是io对象)。

Often, either model can be made to work, but usually one or the other will feel more natural given how modules are being loaded and who has the desired information and how you intend for modules to be reused in other circumstances.

通常,任何一个模型都可以用来工作,但是考虑到模块是如何加载的、谁拥有所需的信息以及您打算如何在其他情况下重用模块,通常一个模型或另一个模型会感觉更自然。

#2


12  

If you want to avoid the global scope, make your io exist in a separate file like this:

如果您希望避免全局作用域,请将您的io保存在如下所示的单独文件中:

var sio = require('socket.io');
var io = null;

exports.io = function () {
  return io;
};

exports.initialize = function(server) {
  io = sio(server);

  io.on('connection', function(socket) {
    // Producer.startProducer();
    /*ditconsumer.start(function(value){
        io.emit('ditConsumer',value);
    });*/
    socket.on('createlogfile', function() {
      logsRecording.userLogs(function(filename) {
        socket.emit('filename', filename);
      });

    });
    socket.on('startrecording', function(filename) {
      console.log('response after creating file', filename);
      logsRecording.recordLogs(filename);
      //value that will be send it to file
    });
  });
};

Then in app.js:

然后在app.js:

var server = require('http').createServer(app);
var io = require('./io').initialize(server);

server.listen(...);

and in consumer.js:

而在consumer.js:

...
var socket = require('../io').io();
...

#3


0  

You can make a singleton instance in just 4 lines.

您可以在仅仅4行中创建一个单例实例。

In websocket.js write your server configuration code.

websocket。编写服务器配置代码。

const socketIO = require('socket.io');
const server = require('http').createServer();
server.listen(8000);

module.exports = socketIO(server);

Then in your consumer.js just require the file

然后在你的消费者。js只需要文件

const socket = require('./websocket');

/* API logic here */

socket.emit('userRegistered', `${user.name} has registered.`);