Question

I am working on a complex game with Nodejs and Socket.io, where I need to store socket.io objects in the memory and also assign properties to the socket object ( say a name , a counter of some action from the socket , etc )

In the code below, I have shown an example of what I am trying to achieve. I store all the sockets in an array and also have another array which stores the name property of the socket. At any time if I get a request for the name, I can just pick the name from the array in the memory.

But now I have too many users and I need to load-balance my application across multiple servers. So I cant store objects and properties in the memory. I need to store them in a Database.

I am planning to use Redis. This link tells how to use Redis Store for sockets -

https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO

But how do I associate my other properties ( say name etc ) to the socket object in the Redis Store ? If there is some new ways to achieve this , please let me know also.

 var socket_array = new Array();
var socket_name_array = new Array();

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {

socket_array.push(socket);
var i = socket_array.indexOf(socket);
var name = generate_random_name();
socket_name_array[i]= name;

  socket.on('get_name', function (data) {

var i = socket_array.indexOf(socket);
var name= socket_name_array[i]
socket.emit('socket_name' , {name :name } );


  });
});

function generate_random_name(){

var random_string;
//code 
return random_string;

}
Was it helpful?

Solution

Yes, if you want to load balance socket.io servers you will have to use a store like redisstore.

However now you should not use "socket_name_array" + events to maintain data consistent across your server.

Setup

var redis = require('redis'),
var pub = redis.createClient(port, host),
var sub = redis.createClient(port, host),
var client = redis.createClient(port, host);

io.configure(function(){
    io.set('store', new RedisStore({
        redisPub: pub,
        redisSub : sub,
        redisClient : client
    }));
});

Usage

io.sockets.on('connection', function (socket) {
  var name = generate_random_name();
  socket.set('name', name); // store it in redis and forward this to other socket.io servers

  // On another server, if you want to retrieve this value from this socket just do:
  socket.get('name', function(err, name){
    // don't forget err. handling
    console.log(name);
  });

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top