Waleed Kasem
Waleed Kasem

Reputation: 13

Nodejs Arrays by Sockets ids

i have socketio on client side which connects to nodejs on the other side so

so my service serv many users at the same time with diffrent data

so there is on nodejs :

   io.on("connect",function(socket){
   var socket.id = []; /// i know this not gonna work

   }):

so i want to make anarray thats holds the data for every socket so i want to get socket id and make an arry with the name of socket id

so i can access every socket by its array

and if i can destroy array with its data on socket disconnect

Thank you :D

Upvotes: 0

Views: 2142

Answers (1)

Sarita
Sarita

Reputation: 847

You can use objects that has socket ID as the key and contains the related data.

var socketio = require("socket.io");
var io = socketio.listen(app);
var socketInfo = {};
io.on("connection",function(socket){
    socketInfo[socket.id]  = [];
    socketInfo[socket.id].socket =  socket;
    socketInfo[socket.id].data =  {}; //store socket related data here

    socket.on('disconnect', function() {
        delete socketInfo[socket.id]
    });
}):

For emitting you could do this:

var socket = socketInfo[socketID].socket;
socket.emit('message', socketInfo[socketID].data);

Upvotes: 1

Related Questions