Skip to content

Instantly share code, notes, and snippets.

@AyemunHossain
Created June 5, 2024 05:08
Show Gist options
  • Save AyemunHossain/b205d2a9f3e0d7e5ac9cf2fcc0d9cd50 to your computer and use it in GitHub Desktop.
Save AyemunHossain/b205d2a9f3e0d7e5ac9cf2fcc0d9cd50 to your computer and use it in GitHub Desktop.
Nodejs Socket and redis example
1. Install dependencies:
npm install express socket.io redis
2. Nodejs Code:
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const redis = require('redis');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
const redisClient = redis.createClient();
io.on('connection', (socket) => {
console.log('New client connected');
socket.on('message', (msg) => {
redisClient.publish('chat', msg);
});
redisClient.subscribe('chat');
redisClient.on('message', (channel, message) => {
socket.emit('message', message);
});
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment