Skip to content

Instantly share code, notes, and snippets.

@imadx
Last active May 17, 2020 18:39
Show Gist options
  • Save imadx/a73156886cbce2fc2265ac05dff97f65 to your computer and use it in GitHub Desktop.
Save imadx/a73156886cbce2fc2265ac05dff97f65 to your computer and use it in GitHub Desktop.
Live User Count with NodeJS and Socket.io
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script>
var socket = io("http://localhost:3000", {
// setting transports to websocket, and not polling
transports: ["websocket"],
});
socket.on("reconnect_attempt", () => {
// setting transports to websocket, and not polling
socket.io.opts.transports = ["websocket"];
});
socket.on("userCount", console.log);
socket.on("error", console.error);
</script>
const WHITELISTED_ORIGINS = ["https://adeka.lk"];
const PORT = process.env.PORT || 3000;
const io = require("socket.io")(PORT);
let userCount = 0;
// Checks if the socket connection is from a whitelisted origin
const isNotWhitelisted = (origin) => {
return WHITELISTED_ORIGINS.indexOf(origin) === -1;
};
// io.emit can be used for broadcasting to all sockets
const emitUserCount = () => {
io.emit("userCount", { userCount });
};
io.on("connection", (socket) => {
if (isNotWhitelisted(socket.handshake.headers.origin)) {
console.log("Origin not white listed:", socket.handshake.headers.origin);
return;
}
// increment user count when on socket connections
userCount++;
emitUserCount();
// decrement user count when socket disconnects
socket.on("disconnect", () => {
userCount--;
emitUserCount();
});
});
console.log("Live User Count server started on %d", PORT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment