javascript Socket.io - 在 node.js 中的单独文件中监听事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23653617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:18:44  来源:igfitidea点击:

Socket.io - listen events in separate files in node.js

javascriptnode.jseventssocket.io

提问by Santos

For example my idea is:

例如我的想法是:

File1.js

文件1.js

 io.sockets.on('connection', function (socket) {
      socket.on('file1Event', function () {
           //logic
      });
 });

File2.js

文件2.js

 io.sockets.on('connection', function (socket) {
      socket.on('file2Event', function () {
           //logic
      });
 });

This code it's for a node server, I will have problems it this code?

此代码用于节点服务器,此代码有问题吗?

回答by eDwaRd

Nope, just use the same "io" object.

不,只需使用相同的“io”对象。

File1.js

文件1.js

exports = module.exports = function(io){
  io.sockets.on('connection', function (socket) {
    socket.on('file1Event', function () {
      console.log('file1Event triggered');
    });
  });
}

File2.js

文件2.js

exports = module.exports = function(io){
  io.sockets.on('connection', function (socket) {
    socket.on('file2Event', function () {
      console.log('file2Event triggered');
    });
  });
}

app.js

应用程序.js

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')
  , file1 = require('./File1')(io)
  , file2 = require('./File2')(io)

app.listen(3000);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

index.html

索引.html

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.emit('file1Event');  // 'file1Event triggered' will be shown
  socket.emit('file2Event');  // 'file2Event triggered' will be shown
</script>

回答by kaligrafy

Be careful not to generate a new connection event for each file. You should use the same on('connection') event, otherwise after 10 files imported, you will get this error from node: MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 connection listeners added. Use emitter.setMaxListeners() to increase limit.

注意不要为每个文件生成一个新的连接事件。您应该使用相同的 on('connection') 事件,否则在导入 10 个文件后,您将从 node: 收到此错误MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 connection listeners added. Use emitter.setMaxListeners() to increase limit

The better way is to do like this in your main file:

更好的方法是在主文件中这样做:

io.on('connection', function (socket) {

  require('pathToSocketRoutesFile1')(socket);
  require('pathToSocketRoutesFile2')(socket);

  require('pathToSocketRoutesFileN')(socket);

  return io;

};

and in each separate file:

并在每个单独的文件中:

module.exports = function(socket) {

  socket.on('eventName1', function() {
    //...
  });

  socket.on('eventName2', function() {
    //...
  });

};

回答by fengelhardt

Another option is to create a rootSocketwhich handles the initial connection and then passes the socket to other handlers.

另一种选择是创建一个rootSocket来处理初始连接,然后将套接字传递给其他处理程序。

const rootSocket = (io) => {
    io.sockets.on('connection', (socket) => {
        authorization(socket);
        chat(socket);
    });
};
exports.default = rootSocket;