gpt4 book ai didi

javascript - 从另一个文件访问 SocketIO

转载 作者:行者123 更新时间:2023-12-04 13:19:51 31 4
gpt4 key购买 nike

我正在尝试向从单独文件连接的所有套接字发出。但是我似乎无法弄清楚。

Socket.js

var socketio = require('socket.io');
var users = require('./modules/users');

var io = socketio();
socket.io = io;

io.on('connection', function(socket){
//Stuff
console.log('Hello :)');
});

module.exports = socket;

用户.js
var socket = require('../socket');

function news(){
socket.io.sockets.emit('news', {
message: 'Woah! Thats new :)'
})
}

setInterval(function(){
news();
}, 5 * 1000);

但是, socket在 users.js 中似乎是空的,我似乎无法访问 io 对象。我怎样才能做到这一点,以便我可以向所有用户发出?没有将 io.sockets 解析为新闻函数或将我的函数移动到套接字文件?

最佳答案

您可以在 utils 和 io 函数中将 io 对象定义为 let 作为全局变量。您可以从任何文件中调用这些函数。例如:

// app.js

const { socketConnection } = require('./utils/socket-io');
const http = require('http');
const express = require('express');

const app = express();
const server = http.createServer(app);
socketConnection(server);

// utils/socket-io

let io;
exports.socketConnection = (server) => {
io = require('socket.io')(server);
io.on('connection', (socket) => {
console.info(`Client connected [id=${socket.id}]`);
socket.join(socket.request._query.id);
socket.on('disconnect', () => {
console.info(`Client disconnected [id=${socket.id}]`);
});
});
};

exports.sendMessage = (roomId, key, message) => io.to(roomId).emit(key, message);

exports.getRooms = () => io.sockets.adapter.rooms;

// any file

const { sendMessage } = require('../utils/socket-io');

const foo = async () => {
const roomId = '12345';
const key = 'new-order';
const message = 'new order assigned';

sendMessage(roomId, key, message);
};

关于javascript - 从另一个文件访问 SocketIO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54818909/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com