NodeJS 如何将socket.io连接导出到其他控制器

1tuwyuhd  于 2023-02-03  发布在  Node.js
关注(0)|答案(3)|浏览(144)

我陷入了一个难题。
我在bin文件中创建了一个socket.io连接,这个连接可以正常工作,但是有没有人能告诉我如何将这个连接导出到不同的控制器。这是我的bin文件代码。

var app = require('../app');
var debug = require('debug')('userservice:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3015');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);
var io = require('socket.io')(server);
io.on('connection', (socket) => {
  console.log('Connection made #######################################################.', socket.id);
  socket.on('disconnect', () => {
    console.log('Connection disconnected @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.', socket.id);
  });
});
/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
3gtaxfhh

3gtaxfhh1#

有很多技术可以用来重用套接字示例,一个简单易行的技术是创建一个单数类,以便能够:
1.启动套接字示例
1.将示例导出到其他模块

套接字.js:

let io;

module.exports = {
  init: (server) => {
    io = require('socket.io').listen(server); io.origins('*:*');
    return io;
  },
  get: () => {
    if (!io) {
      throw new Error("socket is not initialized");
    }
    return io;
  }
};

服务器.js:

const app = require('../app');
const http = require('http');

/**
 * Get port from environment and store in Express.
 */

const port = '3015';
app.set('port', port);

/**
 * Create HTTP server.
 */

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

io.on('connection', (socket) => {
  console.log('Connection success', socket.id);
  socket.on('disconnect', () => {
    console.log('Connection disconnected', socket.id);
  });
}

现在您可以在其他模块中使用它。

const io = require('./socket.js').get();
mrphzbgm

mrphzbgm2#

您只需创建一个socket.io控制器模块,该模块导出一个函数,您可以为每个新连接调用该函数。
因此,在当前服务器文件中,添加以下内容:

const {socketConnected} = require('socketController.');

并且,您可以修改此部分,以便为每个新套接字调用它:

var server = http.createServer(app);
var io = require('socket.io')(server);
io.on('connection', (socket) => {
  console.log('Connection made #######################################################.', socket.id);
  // tell controller about new socket (and pass the io instance)
  socketConnected(socket, io);
  socket.on('disconnect', () => {
    console.log('Connection disconnected @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.', socket.id);
  });
});

然后,你的套接字控制器可以是这样的:

module.exports.socketConnected = function(socket, io) {
    // new socket.io socket connected
    console.log(`controller: got socket.io connection ${socket.id}`);

    // register appropriate event handlers on the socket here
}
r7xajy2e

r7xajy2e3#

我们可以通过创建一个全局对象来导出每个文件中的套接字模块。

let io;
const connectedUsers = [];
const setupSocketIO = function (server) {
  io = require('socket.io')(server, { cors: { origin: '*' } });
  io.on('connection', function (socket) {
    connectedUsers[connectedUsers.length] = socket.id;
    socket.on('getConnectedUsers', () => {
      io.sockets.emit('returnConnectedUsers', connectedUsers.length);
    });
    socket.on('disconnect', () => {
      let socketIdToRemoveIndex = -1;
      for (let i = 0; i < connectedUsers.length; i++) {
        if (connectedUsers[i] === socket.id) {
          socketIdToRemoveIndex = i;
        }
      }
      if (socketIdToRemoveIndex !== -1) {
        connectedUsers.splice(socketIdToRemoveIndex, 1);
      }
      io.sockets.emit('connectedUsers', connectedUsers.length);
    });
  });
};
const Socket = function () {
  return {
    emit: function (event, data) {
      io.sockets.emit(event, data);
    },
    to: function (roomId, event, data) {
      io.sockets.to(roomId).emit(event, data);
    },
  };
};
exports.setupSocketIO = setupSocketIO;
exports.Socket = Socket;

而在文件或组件网中,我们要使用。

const getAllProjects = async (req, res) => {
    let Socket = require('../sockets').Socket();
    Socket.emit('SOCKET_PUSH_NOTIFICATION', { data: 'This is random data' });
    Socket.to('SOCKET_PUSH_NOTIFICATION', 'event', { data: 'Muhammad' });
}

相关问题