demfeels demfeels - 6 months ago 11
Node.js Question

Send a message from client to server on connection node.js

I want my client-side code to send the server the user's userid when establishing the connection, then i want the server to check the database for new messages for each user that is connecting, and send the user the number of new messages it has when new messages are available.

My client-side code:

var socket = io.connect('http://localhost:8000');
socket.on('connect', function () {
socket.emit('userid', '1');
});

socket.on('new_message', function (data) {
var number_of_messages= "<p>"+data.number+"</p>";
$('#container').html(number_of_messages);
});


My server-side code:

io.sockets.on( 'userid', function (data) {

console.log('userid: '+data);

});


My problem is that the above code is not working: the userid is never received by the serverside and the on('userid') is never called.
My question is how to know which socket sent this user id and how to send to only this specific socket a certain message.

Answer

I have solved the problem by saving the clients socket and their id into a global array. this is not a good solution but it works; I know there are rooms and namespaces but I never used it..

socket.io namespaces and rooms

however,

(I used express)

client:

 var socket = io.connect('http://localhost:3000',{reconnection:false});
   socket.once('connect', function() {
        socket.emit('join', '#{id}');
   };

server:

var clients = [];    

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

 socket.on('join', function(data) { 
        clients.push({
            ws: socket,
            id: data
        });
       //retrive the messages from db and loop the clients array
       //and socket.send(things)
    }
}