Here is my code using socket.io as WebSocket and backend with pub/sub redis.
var io = io.listen(server), buffer = []; var redis = require("redis"); var subscribe = redis.createClient(); **<--- open new connection overhead** io.on('connection', function(client) { console.log(client.request.headers.cookie); subscribe.get("..", function (err, replies) { }); subscribe.on("message",function(channel,message) { var msg = { message: [client.sessionId, message] }; buffer.push(msg); if (buffer.length > 15) buffer.shift(); client.send(msg); }); client.on('message', function(message){ }); client.on('disconnect', function(){ subscribe.quit(); }); });
Every new io request will create new redis connection. If someone open browser with 100 tabs then the redis client will open 100 connections. It doesn't look nice.
Is it possible to reuse redis connection if the cookies are same? So if someone open many browser tabs also treat as open 1 connection.
Continuously opening connections without closing is not a good practice. This will not only consume your resources but may also lead to program crash.
The Socket.IO Redis emitter. The @socket.io/redis-emitter package allows you to easily communicate with a group of Socket.IO servers from another Node. js process (server-side). The emitter is also available in other programming languages: Java: https://github.com/sunsus/socket.io-java-emitter.
Redis is a super fast and efficient in-memory, key–value cache and store. It's also known as a data structure server, as the keys can contain strings, lists, sets, hashes and other data structures. Redis is best suited to situations that require data to be retrieved and delivered to the client as quickly as possible.
Actually you are only creating a new redis client for every connection if you are instantiating the client on the "connection" event. What I prefer to do when creating a chat system is to create three redis clients. One for publishing, subscribing, and one for storing values into redis.
for example:
var socketio = require("socket.io") var redis = require("redis") // redis clients var store = redis.createClient() var pub = redis.createClient() var sub = redis.createClient() // ... application paths go here var socket = socketio.listen(app) sub.subscribe("chat") socket.on("connection", function(client){ client.send("welcome!") client.on("message", function(text){ store.incr("messageNextId", function(e, id){ store.hmset("messages:" + id, { uid: client.sessionId, text: text }, function(e, r){ pub.publish("chat", "messages:" + id) }) }) }) client.on("disconnect", function(){ client.broadcast(client.sessionId + " disconnected") }) sub.on("message", function(pattern, key){ store.hgetall(key, function(e, obj){ client.send(obj.uid + ": " + obj.text) }) }) })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With