2017-12-14 5 views
0

특정 클라이언트에게 비공개 메시지를 보내는 데 문제가 있습니다. 이 이벤트 "대화 개인 게시"가 작동하지 않아 고객이이 개인 정보를 볼 수 없습니다.소켓 io를 사용하여 클라이언트에게 비공개 메시지 보내기

나는 무엇이 잘못되었는지 알지 못합니다. 다음과 같이 서버에 객체를 방출

server.js

io.on('connection', function (socket, username) { 
    console.log('New client connected (id=' + socket.id + ').'); 

    socket.on('subscribe', function(room) { 
     console.log('joining room', room); 
     socket.join(room); 
    }); 

    socket.on('send message', function(data) { 
     console.log('sending room post', data.room); 
     socket.to(data.room).emit('conversation private post', { 
      message: data.message 
     }); 
    }); 
}); 

client.js 클라이언트에

<html> 

    <head> 
    <title>Getting started with Sockets</title> 
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script> 

    <script> 
     var conversation_id = Math.floor(Math.random() * 1000) 
     var socket = io('http://localhost:3000'); 
     socket.emit('subscribe', conversation_id); 

     socket.emit('send message', { 
      room: conversation_id, 
      message: "Some message" 
     }); 

     socket.on('conversation private post', function(data) { 
      console.log("Private conversation", data) 
     }); 
    </script> 

    </head> 

    <body> 
    <div id="serverMsg">Waiting for the message from server:</div> 
    </body> 

</html> 
+0

개인 메시지를 보내려는 각 회의실/사용자 쌍마다 다른 pub-sub 채널을 사용하는 것이 해결책 일 수 있습니다. 현재'send message' 이벤트에서'room'의 모든 사용자에게 메시지를 브로드 캐스트합니다. – sayan

+0

서버 쪽에서'send message'를 디버깅 했습니까? 'data.room'은 예상대로 통과합니까? –

답변

0

:

내 코드입니다 데이터 :

{ 
    to: [the other receiver's username as a string] , 
    from: [the person who sent the message as string] , 
    message: [the message to be sent as string] 
} 

서버에서 메시지를 수신하십시오. 메시지가 수신되면 데이터를 수신자에게 내 보냅니다.

"the user you want to send"[data.to].emit('receivedMessage', data)