我编写了一个简单的套接字程序,用于将多个客户端与服务器连接起来并且工作正常。如果我发送任何消息,它将到达所有客户端。但是我需要发送一个指定的客户端进行私人聊天。那我该怎么办呢?
客户代码
function showMessage(messageHTML) {
$('#chat-box').append(messageHTML);
}
$(document).ready(function(){
var websocket = new WebSocket("ws://localhost:8090/php/Chat/simple-php-chat/php-socket.php");
websocket.onopen = function(event) {
showMessage("<div class='chat-connection-ack'>Connection is established!</div>");
}
websocket.onmessage = function(event) {
var Data = JSON.parse(event.data);
showMessage("<div class='"+Data.message_type+"'>"+Data.message+"</div>");
//alert(Data.message);
$('#chat-message').val('');
};
websocket.onerror = function(event){
showMessage("<div class='error'>Problem due to some Error</div>");
};
websocket.onclose = function(event){
showMessage("<div class='chat-connection-ack'>Connection Closed</div>");
};
$('#frmChat').on("submit",function(event){
event.preventDefault();
$('#chat-user').attr("type","hidden");
var messageJSON = {
chat_user: $('#chat-user').val(),
chat_message: $('#chat-message').val(),
chat_to: $('#chat-to').val()
};
websocket.send(JSON.stringify(messageJSON));
});
});