I'm trying to emit to all the sockets connected from a seperate file. However I cannot seem to figure it out.
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;
Users.js
var socket = require('../socket');
function news(){
socket.io.sockets.emit('news', {
message: 'Woah! Thats new :)'
})
}
setInterval(function(){
news();
}, 5 * 1000);
However, socket in users.js seems to be empty and I can't seem to access to io object. How can I make it so I can emit to all users? Without parsing the io.sockets to the news function or moving my function to the socket file?
You can define io object with let as global variable in utils and io functions there. You can call these functions from any file. For example:
// 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);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With