[英]Socket.io emits not always recieved on Node.js + Redis + Heroku (multiple dynos) environment
我們在Heroku上運行了一個帶有Socket.io v0.9.16
的Node.js v0.10.25
應用程序。 我們使用redis v2.6
,更具體地說是Heroku附加組件“redis to go”,作為套接字商店。 我們目前有兩個dynos在運行。
問題是通過xhr-polling
的套接字連接被發送到套接字但不總是在同一套接字上接收。 一個例子:
服務器端代碼
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(3001);
var RedisStore = require('socket.io/lib/stores/redis')
var redis = require('redis')
var rtg = require("url").parse(FULL_REDIS_PATH);
var hostname = rtg.hostname;
var database = rtg.auth.split(":")[0];
var portRedis = rtg.port;
var password = rtg.auth.split(":")[1];
var pub = redis.createClient(portRedis, hostname)
var sub = redis.createClient(portRedis, hostname)
var client = redis.createClient(portRedis, hostname)
pub.auth(password, function (err) { if (err) throw err; });
sub.auth(password, function (err) { if (err) throw err; });
client.auth(password, function (err) { if (err) throw err; });
/** Initialize RedisStore for socket.io **/
io.set('store', new RedisStore({
redis : redis
, redisPub : pub
, redisSub : sub
, redisClient : client
}));
/** Configuration Settings for socket.io **/
io.set('log level', 1);
io.set('transports', ['flashsocket','xhr-polling']);
io.set('polling duration', 10);
io.sockets.on('connection', function (socket) {
/** Associate Client ID to Socket ID **/
client.set('client-'+client_id,socket.id, function(err){
if (err) throw err;
console.log("User " + client_id + " socket is now... " + socket.id);
/**
* Retrieve the Socket ID by the User's ID
* Send a socket.emit message based on the Socket ID retrieved from Redis.
**/
client.get('client-'+client_id,function(err, response){
socketId = response;
io.sockets.socket(socketId).emit('response',{user_id: client_id});
console.log('Retrieving User ' + client_id + ' - socket is now... ' + socket.id);
});
});
});
客戶端代碼
<script src="http://localhost:3001/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3001');
socket.on('response', function (data) {
console.log(data);
});
</script>
對此有任何幫助將非常感謝,提前感謝!
如果“我們目前有兩個dynos在運行”。 你的意思是你有兩個你的服務器實例,通過redis pub / sub進行通信,那么這應該是你的ooking: http ://socket.io/docs/using-multiple-nodes/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.