4

Following code is for socket.io server in node.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var clients=[];
var gamename={};

io.on('connection', function(socket){
  socket.on('game', function(data){
    gamename[data.gamename]=data.number; //problem is here 
  });
});

gamename=name of the game; number= user id;

  1. there can be more number of games;
  2. there can be more number of users per game

and I am emitting game event in the client side with some data (includeing gamename, and number)whenever a connection is established with the server. So whenever a new client connects to the server the game event is triggered in the server. In the game event in the server side I want to push "number" to the object property gamename(variable).

example:

var games={};

whenever there is a connection for example for the game poker with user id 34 I want to do var gamename='poker';

 gamename[gamename] -> I want this automatically created as array, or   anything, but I want to push user id's.

the resulting objecting should be.

games={'poker' : [34]};

If I one more user connects for poker with user id 45,

games={'poker' : [34, 45]};

and If a a user connects for game cricket with user 67

games={'poker' : [34, 45],'cricket' : [67]};

Initial object

games={};

after some connections(there can be n number of connections)

games={'poker' : [34, 45],'cricket' : [67]};

If my question is not clear I will explain it in detail if anybody asks. Thanks in advance

1 Answer 1

7

Like this:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var clients=[];
var gamename={};

io.on('connection', function(socket){
  socket.on('game', function(data){
    gamename[data.gamename] = gamename[data.gamename] || [];
    gamename[data.gamename].push( data.number ); //no more problem 
  });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, But could you please explain what this line does gamename[data.gamename] = gamename[data.gamename] || []; I am new to javascript
it initializes the gamename[data.gamename] to an empty array if it's not already initialized.
yw, please accept my answer if it solved your problem :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.