Studento919 Studento919 - 3 months ago 16
Node.js Question

Socket.io - Cant stop passing all data to all clients

I am having a issue where I am pulling data from a DB via node mysql & Express and passing it via socket.io.... but there's an issue am running into.

All users are updating with the same data rather than unique data per user.

For example:

If user A has just logged in he can see all his account details. But when user B logs in right after he can then see all his details....but it then updates user A details to show user B details as well.

I am trying to ensure user A can can only see his own and same for user B.

I have tried numerous things to stop this happening via JQuery but cant seem to find a resolution.

Below I have trimmed down a the code to a basic example:

HTML

<a href=""><span id="id-val">User A</span></a>
<a href=""><span id="user-val"></span></a>


Server side

server = http.createServer(app),
io = require('socket.io').listen(server);

function SQLuserData(userval) {
connection.getConnection(function (err, connection) {
connection.query('SELECT val FROM test WHERE name= ?;',
[userval],
function (err, rows) {
var accountval = rows[0]['val'];
if (accountval) {
console.log("Val : " + accountval);
UserVal(accountval);
} else {
console.log("Error | Val: " + err);
}
});
connection.release();
});
}

//Socket.io connection socket
io.sockets.on('connection', function (socket) {
socket.on('sqluser', function (userval) {
SQLuserData(userval);
});
});

//Pass val client side.
function UserVal(accountval) {
io.sockets.emit("valsocket", accountval);
}


Client side

var socket = io.connect();
//Used to grab information for that user from serverside.
$(document).ready(function () {
var userval = $('#id-val').text();
socket.emit('sqluser', userval);
});

//Grabs user value being passed from serverside and updates HTML.
socket.on("valsocket", function (accountval) {
$("#user_val").val(accountval);
});


Does anyone have any advice or potential solutions?

JAG JAG
Answer

you need to grab and store the socket.id for each connected user

var users = {};

//Socket.io connection socket
io.sockets.on('connection', function (socket) {
    socket.on('sqluser', function (userval) {  
        // 'userval' must be unique for each user
        users[userval] = socket.id;
        SQLuserData(userval);
    });
});

and then use the same id to emit data ti single socket

//Pass val client side.
function UserVal(accountval, userval) {
    io.sockets.socket(users[userval]).emit("valsocket", accountval);
}

for socket.io version 1.0 and above

io.to(users[userval]).emit("valsocket", accountval);