Skip to content

Instantly share code, notes, and snippets.

@m4rk3r
Last active February 17, 2021 21:58
Show Gist options
  • Save m4rk3r/bf1a3ad0e3ab9e0608fc0a03cafebc58 to your computer and use it in GitHub Desktop.
Save m4rk3r/bf1a3ad0e3ab9e0608fc0a03cafebc58 to your computer and use it in GitHub Desktop.
const Redis = require('ioredis');
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const io = require('socket.io')(server);
const redis = new Redis();
const redisAdapter = require('socket.io-redis');
io.adapter(redisAdapter({ host: 'localhost', port: 6379 }));
const key = 'sia:viewers';
// clear key on restart
redis.del(key);
const notify = async () => {
const viewers = await redis.scard(key);
io.emit('update', { viewers });
}
io.on('connection', async (socket) => {
console.log('socket connected..');
if (!await redis.sismember(key, socket.id)) {
await redis.sadd(key, socket.id);
}
// notify others
notify();
socket.on('disconnect', async () => {
await redis.srem(key, socket.id);
notify();
})
});
server.listen(3000, () => {
console.log('server started');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment