2014-06-24 2 views
0

나에게 지정된 특정 ID를 가진 사용자에게만 메시지를 보내려면 어떻게해야합니까?socket.io를 사용하여 특정 사용자에게 메시지를 보내는 방법은 무엇입니까?

예를 들어, id = 5 인 사용자가 있으며 연결된 모든 사용자가 아닌 해당 사용자에게만 메시지를 보내려고합니다. 연결될 때이 ID를 서버로 어떻게 보내야합니까? 전혀 가능합니까?

클라이언트 당신은 핸드 쉐이크 동안 클라이언트에서 서버로 사용자 ID를 전달하고 사용자 그룹 (예를 들어, "USER5")을 가입 할 수 있습니다

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

답변

3

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

서버.

클라이언트 측 :

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 
}); 
그럼 당신은이 그룹에 방출 할 수있다
관련 문제