chandradot99
chandradot99

Reputation: 3866

how to get socketid in socket.io(nodejs)

In my nodejs application, i am using socket.io for sockets connection.

I am configuring my server side code like this

socket.io configuration in separate file.

//socket_io.js

var socket_io = require('socket.io');
var io = socket_io();
var socketApi = {};

socketApi.io = io;

module.exports = socketApi;

below is my server.js file in which i am attaching my socket io to the server like this

var socketApi = require('./server/socket_io');


// Create HTTP server.
const server = http.createServer(app);

// Attach Socket IO
var io = socketApi.io;
io.attach(server);


// Listen on provided port, on all network interfaces.
server.listen(port, () => console.log(`API running on localhost:${port}`));

and then i am using socket.io in my game.js file to emit updated user coins like this.

 //game.js

 var socketIO = require('../socket_io');

 function updateUserCoins(userBet) {
    userId = mongoose.Types.ObjectId(userBet.user);

    User.findUserWithId(userId).then((user) => {
        user.coins = user.coins - userBet.betAmount;

        user.save((err, updatedUser) => {
            socketIO.io.sockets.emit('user coins', {
                userCoins: updatedUser.coins,
            });
        });

    })
}

and then in my client side, i am doing something like this,

socket.on('user coins', (data) => {
  this.coins = data.userCoins;
});

but with the above implementation, updating coins of any user, updates all user coins at the client side, since all the clients are listening to the same socket user coins.

To solve the above problem, i know that i have to do something like this,

// sending to individual socketid (private message)
socketIO.io.sockets.to(<socketid>).emit('user coins', {
    userCoins: updatedUser.coins,
});

but my concern is that how will get <socketid> with my current implementation.

Upvotes: 1

Views: 1178

Answers (1)

mJehanno
mJehanno

Reputation: 866

You can get it by listening to connection to your socket.io server :

io.on('connection', function (socket) {
   socket.emit('news', { hello: 'world' });
   socket.on('my other event', function (data) {
     console.log(data);
   });
});

Here you have a socket object ( io.on('connection', function (socket) ) and you can get his id with socket.id

So you'll probably need to wrap your code with the connection listener.

Source of the exemple for the connection listener

Socket object description

Upvotes: 0

Related Questions