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;
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
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
});
});
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