"Node js Sockets with seperate file"
Bootstrap 4.1.1 Snippet by Arjunverma

<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!------ Include the above in your HEAD tag ----------> <div class="container"> <div class="row"> <h2>Node js Sockets with seperate file</h2> </div> </div> <!--sever file yani main file--> const express = require('express'); const mongoose = require('mongoose'); const cors = require('cors'); const path = require('path'); const { createServer } = require('http'); const { Server } = require('socket.io'); // Correct import for Socket.IO const { setupSocket, activeUsers } = require('./sockets/socket'); require('dotenv').config(); const app = express(); const server = createServer(app); // HTTP server for Express and Socket.IO // Middlewares app.use(express.json()); app.use(express.static(path.join(__dirname, 'upload'))); // Create Socket.IO server const io = new Server(server, { cors: { origin: '*', // Allow all origins for simplicity, but configure this for production methods: ['GET', 'POST'] } }); //Sockets funtions and events setupSocket(io); // Routes app.get('/', (req, res) => { res.send('Project is Running Smoothly!!'); }); // API to get all active users app.get('/active-users', (req, res) => { res.json({ activeUsers: Object.values(activeUsers) }); // Send array of user data }); // Server Listener const PORT = process.env.PORT || 3600; server.listen(PORT, () => { console.log(`Project is running on http://localhost:${PORT}`); });
/*Seperate sockets file in socket folder /socket.js */ // Initialize an object to keep track of active users const activeUsers = {}; // Define the setupSocket function to handle socket events const setupSocket = (io) => { io.on('connection', (socket) => { console.log('A user connected:', socket.id); // Listen for the 'online' event to add a user socket.on('online', (data) => { const { user } = data; if (user) { activeUsers[socket.id] = user; // Add user to activeUsers console.log(`User joined: ${user}`); } // Broadcast the updated active user list to all clients io.emit('activeUsers', Object.values(activeUsers)); }); // Listen for the 'offline' event to remove a user socket.on('offline', (data) => { const user = activeUsers[socket.id]; delete activeUsers[socket.id]; // Remove the user from activeUsers console.log(`${user} is logged out!!`); // Broadcast the updated active user list to all clients io.emit('activeUsers', Object.values(activeUsers)); }); // Handle disconnections and remove user socket.on('disconnect', () => { const user = activeUsers[socket.id]; delete activeUsers[socket.id]; // Remove user from activeUsers console.log(`User disconnected: ${user || 'Unknown'}`); // Broadcast the updated active user list to all clients io.emit('activeUsers', Object.values(activeUsers)); }); }); }; // Export the setupSocket function module.exports = { setupSocket, activeUsers };

Related: See More


Questions / Comments: