【问题标题】:How to send a message to specific user with socket.io?如何使用 socket.io 向特定用户发送消息?
【发布时间】:2014-08-14 11:51:21
【问题描述】:

如何仅向具有我指定的特定 ID 的用户发送消息?

例如,我有一个 id=5 的用户,我只想向他发送消息,而不是向所有连接的人发送消息。当他连接时,这个 id 应该如何发送到服务器?有可能吗?

客户

<?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>

服务器

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

【问题讨论】:

    标签: php sockets websocket socket.io chat


    【解决方案1】:

    您可以在握手时将用户 ID 从客户端传递到服务器并让用户加入群组(例如“user5”)。然后你可以发射到这个组:

    客户端:

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

    服务器端:

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

    【讨论】:

      猜你喜欢
      • 2012-07-08
      • 2021-04-10
      • 1970-01-01
      • 2011-06-06
      • 2011-10-18
      • 1970-01-01
      • 2015-04-27
      • 1970-01-01
      相关资源
      最近更新 更多