How to send message only to a user with Websocket

Asked

Viewed 996 times

2

I have a live chat app with Websocket, but at the moment it sends messages to the entire group, I would like to know how to send to a selected user, in case when I click the user (from a list that appears beside) he start a conversation with that due user.

<?php
$pdo = new PDO('mysql:host=localhost;dbname=chat-websocket', 'root', '');

session_start();
include_once 'config.php';
require_once("classes/BD.class.php");
BD::conn();

date_default_timezone_set('America/Sao_Paulo');

if ($_SESSION['logado'] != 1) {
    header("Location: login.php");
} else {
?>
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8' />
<style type="text/css">
<!--
.chat_wrapper {
    width: 700px;
    margin-right: auto;
    margin-left: auto;
    background: #CCCCCC;
    border: 1px solid #999999;
    padding: 10px;
    font: 12px 'lucida grande',tahoma,verdana,arial,sans-serif;
    overflow: hidden;
}
.amigos {
  padding-top: 10px;
  padding-bottom: 10px;
}
p.nome {
  margin: 0;
}   
.usuarios {
  width: 200px;
  float: left;
  height: 172px;
}
.box_mensagem {
  width: 500px;
  float: right;
}
.chat_wrapper .message_box {
    background: #FFFFFF;
    height: 150px;
    overflow: auto;
    padding: 10px;
    border: 1px solid #999999;
}
.chat_wrapper .panel input{
    padding: 2px 2px 2px 5px;
}
.system_msg{color: #BDBDBD;font-style: italic;}
.user_name{font-weight:bold;}
.user_message{color: #88B6E0;}
-->
</style>
</head>
<body>  
<?php
    echo "<div class='nome'>{$_SESSION['usuario']}</div>";
    $colours     = array(
        '007AFF',
        'FF7000',
        'FF7000',
        '15E25F',
        'CFC700',
        'CFC700',
        'CF1100',
        'CF00BE',
        'F00'
    );
    $user_colour = array_rand($colours);
?>

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<script type="text/javascript">
    function notifyMe(nome, mensagem) {
          if (!Notification) {
            alert('Notifications are supported in modern versions of Chrome, Firefox, Opera and Firefox.'); 
            return;
          }

          if (Notification.permission !== "granted")
            Notification.requestPermission();

          var notification = new Notification( nome, {
            icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
            body: mensagem,
          });

          notification.onclick = function () {
            window.open("http://stackoverflow.com/a/13328397/1269037");      
          };
    }
</script>

<script language="javascript" type="text/javascript">  
$(document).ready(function(){
    //create a new WebSocket object.
    var wsUri = "ws://127.0.0.1:9000/pullchat/server.php";
    websocket = new WebSocket(wsUri); 

    websocket.onopen = function(ev) { // connection is open 
        $('#message_box').append("<div class=\"system_msg\">Connected!</div>"); //notify user
    }

    $('#send-btn').click(function(){ //use clicks message send button   
        var mymessage = $('#message').val(); //get message text
        var myname = $('.nome').text(); //get user name
        var mensagem = 'mensagem='+mymessage;

        $.ajax({
            type: 'POST',
            url : 'sys/teste.php',
            data: 'nome='+myname+'&mensagem='+mymessage,
            success: function(html){}
        });

        /*if(myname == ""){ //empty name?
            alert("Enter your Name please!");
            return;
        }*/
        if(mymessage == ""){ //emtpy message?
            alert("Enter Some message Please!");
            return;
        }

        //prepare json data
        var msg = {
        message: mymessage,
        name: myname,
        color : '<?php
    echo $colours[$user_colour];
?>'
        };
        //convert and send data to server
        websocket.send(JSON.stringify(msg));

    });

    //#### Message received from server?
    websocket.onmessage = function(ev) {
        var msg = JSON.parse(ev.data); //PHP sends Json data
        var type = msg.type; //message type
        var umsg = msg.message; //message text
        var uname = msg.name; //user name
        var ucolor = msg.color; //color
        var myname = $('.nome').text(); 
        //var compara = uname.localeCompare(myname);

        if(type == 'usermsg') 
        {
            if(myname != uname){
                notifyMe(uname, umsg);
                $('#message_box').append("<div><span class=\"user_name outro\" nome=\""+uname+"\" style=\"color:#"+ucolor+"\">"+uname+"</span> : <span class=\"user_message\">"+umsg+"</span></div>");
            }else{
                $('#message_box').append("<div><span class=\"user_name\" nome=\""+uname+"\" style=\"color:#"+ucolor+"\">"+uname+"</span> : <span class=\"user_message\">"+umsg+"</span></div>");
            }


        }
        if(type == 'system')
        {
            $('#message_box').append("<div class=\"system_msg\">"+umsg+"</div>");

        }

        $('#message').val(''); //reset text
    };

    websocket.onerror   = function(ev){$('#message_box').append("<div class=\"system_error\">Error Occurred - "+ev.data+"</div>");}; 
    websocket.onclose   = function(ev){$('#message_box').append("<div class=\"system_msg\">Connection Closed</div>");}; 



});
</script>
<div class="chat_wrapper">
<div class="usuarios">
<?php
    $id_user  = $_SESSION['id_user'];
    $sel_user = $pdo->prepare("SELECT * FROM usuarios WHERE id != ?");
    $sel_user->execute(array(
        $id_user
    ));

    while ($fetch = $sel_user->fetchObject()) {
?>
    <div class="amigos">
    <p class="nome" id="<?php
        echo $fetch->id;
?>"><?php
        echo $fetch->nome;
?></p>
    </div>

<?php
    }
?>
</div>
<div class="box_mensagem">
    <div class="message_box" id="message_box">
        <?php
    $select = $pdo->prepare("SELECT * FROM mensagem");
    $select->execute();
    while ($ft = $select->fetchObject()) {
?>
                <div><span class="user_name" style="color:#15E25F"><?php
        echo $ft->nome;
?></span> : <span class="user_message"><?php
        echo $ft->msg;
?></span></div>
            <?php
    }
?>


    </div>
    <div class="panel">
    <!--<input type="text" name="name" id="name" placeholder="Your Name" maxlength="10" style="width:20%"  />-->
    <input type="text" name="message" id="message" placeholder="Message" maxlength="80" style="width:60%" />
    <button id="send-btn">Send</button>
    </div>
</div>
</div>
<div class="response"><a href="logout.php">SAIR</a></div>
</body>
</html>
<?php
}
?>
  • http://answall.com/questions/61002/enviar-messagingpara-usu%C3%A1rio-espec%C3%Adfico-em-websocket-php

1 answer

1


1 - think of sender/recipient

2 - Sender sends message and recipient to socket(ex: login).

3 - All "listeners" of the socket receive the message, but you have to make a filter to check if the listener is equal to the recipient of the message, if it is shows the message, if it is not returns without doing anything.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.