How to send messages only to users with a specific ID?

For example, I have a user with id = 5 and I want to send a message only to him, not to all users connected to the socket. How can I send this id to the server?

Client

<?php $id=5; // id to send to echo ' <div id="id">'.$id.'</div> <div id="messages"></div> <input type="text" id="type"> <div id="btn">Press</div> '; ?> <script> $(document).ready(function(){ var id=$('#id').html(); var socket=io.connect('http://localhost:8010'); socket.on('connecting',function(){alert('Connecting');}); socket.on('connect',function(){alert('Connected');}); socket.on('message',function(data){message(data.text);}); function message(text){$('#messages').append(text+'<br>');} $('#btn').click(function(){ var text=$('#type').val(); socket.emit("message",{text:text}); }); }); </script> 

Server

 io.sockets.on('connection',function(client){ client.on('message',function(message){ try{ client.emit('message',message); client.broadcast.emit('message', message); }catch(e){ console.log(e); client.disconnect(); } }); }); 

How to transfer id = 5 to the server?

    1 answer 1

     io.sockets.on('connection', function (socket) { users.push(socket.id); }); io.on('connection', function(socket){ socket.on('message', function(message) { // если такой пользователь существует if(users[message.user_id] != undefined) { // отправляем только ему сообщение io.sockets.connected[users[message.user_id]].emit('message', message); } }); }); 

    Like that. The user is connected, we bring it in an array. Then just send the key number in the array (i.e., to whom we want the message to arrive).

     socket.emit("message", { 'user_id' : document.getElementById('user_id').value, 'message' : document.getElementById('message').value }); 
    • The problem is that document.getElementById ('user_id'). Value is not socket.id ... Pass the user_id to the server and add it to the users array, or pass the socket.id to the client-file. Preferably the first. - aspermag
    • Well, they say to you - bind sockets to users - make an array, then send user_id and get a link to socket_id, to which you send a message. (@lampa and why this crocodile, why not socket into the users array, do not add?, and then emit it and do it) - zb