实际上,如果要在“连接”事件上实例化客户端,则只为每个连接创建一个新的Redis客户端。创建聊天系统时,我更喜欢创建三个Redis客户端。一种用于发布,订阅,另一种用于将值存储到Redis中。
例如:
var socketio = require("socket.io")var redis = require("redis")// redis clientsvar store = redis.createClient()var pub = redis.createClient()var sub = redis.createClient()// ... application paths go herevar 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) }) })})
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)