nodeJS,express和socketio-如何在多个文件上具有相同的套接字实例?

时间:2020-09-20 15:17:38

标签: node.js express socket.io reusability

因此,我目前在我的应用中有两个文件。主服务器和一个具有其他逻辑的单独文件。这些是服务器上而不是浏览器中的文件。在服务器中,可以通过以下初始化使用socket.io:

//Main server
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);

// Later on when doing socket stuff...

io.on
('connection', socket => 
{   socket.on
    (   'requestStatus', () =>
        {   
//Stuff I want to do goes here.  Effectively, this part I want to be reusable in file #2..

        }
    );
}
);

在另一个文件中,我只想向服务器发送一些内容,然后服务器又将其发送到外部文件。唯一的问题是,似乎有些东西需要从服务器导出,或者我找不到其他步骤。

//File #2 (the file is one class, but this is the relevant function within the class)
//Effectively, when convert() is called, I want to emit a status request to the server.
convert()
{   socket.emit('requestStatus');
    return;
}

我在服务器上尝试过的一件事是:

module.exports = io;

在文件#2中(这当然不起作用)

const io = require('./server');

我在这里不知所措。如果有人能看到我所缺少的内容,或者有人能看到更好的方法,我将不胜感激。预先感谢。

0 个答案:

没有答案