"Sockets.Io In Node js with different 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>Sockets/Server.js</h2> </div> </div> const socketIo = require('socket.io'); const app = express(); const server = http.createServer(app); //Sockets Cors const io = socketIo(server, { cors: { origin: 'http://localhost:5173', // Use a specific origin methods: ['GET', 'POST'], credentials: true } }); setupSocket(io); // Set up socket events module.exports = { io }; // Export io for other files (to avoid circular dependency)
let activeUsers = {}; const setupSocket = (io) => { io.on('connection', (socket) => { console.log(`User connected: ${socket.id}`); // Handle user disconnect socket.on('disconnect', () => { console.log(`User disconnected: ${socket.id}`); Object.keys(activeUsers).forEach((userId) => { if (activeUsers[userId] === socket.id) { delete activeUsers[userId]; } }); }); }); }; module.exports = { setupSocket };

Related: See More


Questions / Comments: