Issue
I got the above exception when I try to implement socket.io
to count active users, i tried every solution but nothing works for me.
Server:
const express = require("express");
const app = express();
const cors = require("cors");
const socketIo = require('socket.io');
const http = require('http');
//Enable CORS policy
app.use(cors());
app.options("*", cors());
//socket io
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origins: ["http://localhost:4200", "http://localhost:3000"],
methods: ["GET", "POST"],
credentials: false
}
});
var count = 0;
io.on('connection', (socket) => {
console.log("Client connected");
if (socket.handshake.headers.origin === "http://localhost:3000") {
count++;
socket.broadcast.emit('count', count);
socket.on('disconnect', () => {
count--;
socket.broadcast.emit('count', count);
});
}
});
//Server
app.listen(8080, () => {
console.log("Server is running on port 8080");
});
Solution
Change this:
app.listen(8080, () => {
console.log("Server is running on port 8080");
});
To this:
server.listen(8080, () => {
console.log("Server is running on port 8080");
});
You are facing this issue because the instance you’ve passed when initializing socket
and instance you are listening to are different.
For more refer this:
Should I create a route specific for SocketIO?