Carolina Ramirez
Carolina Ramirez

Reputation: 31

Sending Data to Target Client with socket.io

For example, in the client side, i have two registred and online user.

UID 1 : Leon
UID 2 : Albert

Leon wants to know how much have credit.

for example, Leon hit the button to get credit, so:

socket.emit('my_credit', 1);

And in the server side, i use this code:

Example:

var express = require('express');
var server  = express();
var app    = require('http').createServer(server);
var io     = module.exports.io = require('socket.io')(app);

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

    socket.on('my_credit', function(uid){
       getUserCredit(uid, (result) => {
            socket.emit('my_credit', result);
        })
    });

});

Now, in the client side, all users receive this value! If I want only Leon to receive this value, how can i do ?

How can i do in the server side to find currect id ?

Upvotes: 1

Views: 557

Answers (2)

Pedroxam
Pedroxam

Reputation: 27

For sending message to target client, use to function:

Eg:

io.sockets.to(/* Unique ID */).emit('message');

Or:

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

    socket.on('check', function(){
        io.sockets.to(socket.id).emit('check', 'Just You: ' + socket.id);
    });

});

Upvotes: 2

koro
koro

Reputation: 111

Yo! So basically, at the moment, I dont know any other solutions than checking socket id. Example to emit client side:

socket.emit('my_credit', {user: 1, id: socket.id});

Receiving server side :

var express = require('express');
var server  = express();
var app    = require('http').createServer(server);
var io     = module.exports.io = require('socket.io')(app);

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

    socket.on('my_credit', function(uid){
        getUserCredit(uid.user, function(result){
            socket.emit('my_credit', {res: result, id: uid.id});
        })
    });

});

And receiving client side :

socket.on('my_credit', (message) => {
if (message.id !== socket.id) return;
// your code here
})

Upvotes: 1

Related Questions