简体   繁体   English

如何使用socket.io向特定用户发送消息?

[英]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? 如何仅将邮件发送给我指定的具有特定ID的用户?

For example, I have a user with id=5 and I want send a message only to him, not to all the connected. 例如,我有一个id = 5的用户,我只想向他发送一条消息,而不是向所有连接的用户发送消息。 How should this id be sent to server when he's connecting? 当他连接时,该ID应该如何发送到服务器? 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();
        }
    });
});

You may pass user ID from client to server while handshaking and make user join the group (eg "user5"). 您可以在握手时将用户ID从客户端传递到服务器,并使用户加入组(例如“ 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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM