Created
June 5, 2024 05:08
-
-
Save AyemunHossain/b205d2a9f3e0d7e5ac9cf2fcc0d9cd50 to your computer and use it in GitHub Desktop.
Nodejs Socket and redis example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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