Search code examples
phpsocketswebsocketsocket.iochat

How to send a message to specific user with socket.io?


How can I send messages only to users with specific IDs, which are specified by me?

For example, I have a user with id=5 and I want send a message only to him, not to all the connected. How should this id be sent to server when he's connecting? Is it possible at all?

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();
        }
    });
});

Solution

  • You may pass user ID from client to server while handshaking and make user join the group (e.g. "user5"). Then you can emit to this group:

    client side:

    var id=$('#id').html();
    var socket=io.connect('http://localhost:8010', {
        query: 'userId=' + id
    });
    

    server side:

    io.sockets.on('connection',function(client){
        var userId = client.handshake.query.userId;
        client.join('user' + userId);
        //from now each client joins his personal group...
        //... and you can send a message to user with id=5 like this:
        io.to('user5').emit('test', 'hello');
    
        //your further code
    });