2016-05-13 84 views
1

我是一個使用nodejs的noob,但試圖與一些用戶創建聊天室,但它現在可以工作,但現在我想在聊天中發送帶有「/ w」命令的私人消息,例如:Nodejs在聊天中使用「/ w」的私人消息

/w大衛你好,你好嗎?

只有大衛可以閱讀味精。 問題是每個人都可以閱讀我的私人消息,例如大衛,從所有用戶接收它,wtf?

這是我server.js

//Création d'un serveur 
var http = require('http'); 
var md5 = require('MD5'); 
var io = require('socket.io'); 

function rand(){ 
    return (Math.round(Math.random())-0.5); 
} 

var colors = new Array('#a8291a','#a5992f','#f24816','#24dc61','#a7954a','#b2676e','#ec4458'); 

//Démarrage du serveur. 
httpServer = http.createServer(function(req,res){ 
    console.log('Page affichée par un utilisateur'); 
}) 

httpServer.listen('4120'); 

var users = {}; 
var clients = []; 
/** 
* Installation socket.io : npm install socket.io 
*/ 

io = io.listen(httpServer); 


io.sockets.on('connection', function(socket){ 

    var me = false; 

    for(var k in users){ 
     socket.emit('newuser', users[k]); 
    } 


    /** 
    * Reception de message. 
    **/ 

    socket.on('newmsg',function(message){ 
     message.user = me; 
     date = new Date(); 
     message.h = date.getHours(); 
     message.m = date.getMinutes(); 
     message.s = date.getSeconds(); 
     io.sockets.emit('newmsg', message); 
    }); 

    /** 
    * Connexion. 
    **/ 

    socket.on('login', function(user){ 
     var hs = socket.handshake; 
     me = user; 
     me.id = user.mail.replace('@','-').replace('.','-'); 
     me.avatar = 'https://gravatar.com/avatar/' + md5(user.mail) + '?s=32&d=identicon'; 
     me.color = colors[Math.floor(Math.random()*colors.length)]; 
     clients[me.id] = socket.id; 
     socket.emit('logged'); 
     users[me.id] = me; 
     //io.sockets.emit permet d'envoyer l'action à tous les utilisateurs. 
     io.sockets.emit('newuser',me); 
    }); 

    /** 
    * Inscription à une room. 
    **/ 

    socket.on("private", function(data) { 
     io.to(clients[data.dest]).emit("private", { from: me.id, to: data.dest, msg: data.msg }); 
     io.to(clients[me.id]).emit("private", { from: me.id, to: data.dest, msg: data.msg }); 
    }); 

    /** 
    * Deconnexion. 
    **/ 
    socket.on('disconnect', function(){ 
     if(!me) 
      return false; 
     delete users[me.id]; 
     io.sockets.emit('discuser',me); 
    }) 
}); 

這是我client.js

(function($){ 

    var socket = io.connect('http://192.168.1.72:4120'); 
    var msg = $('#msg').html(); 
    $('#msg').remove(); 

    $('#loginform').submit(function(event){ 
     event.preventDefault(); 
     socket.emit('login', { 
      username : $('#username').val(), 
      mail : $('#mail').val() 
     }) 
    }); 

    socket.on('logged', function(){ 
     $('#login').fadeOut(); 
     $('#form').fadeIn(); 
     $('#messages').fadeIn(); 
     $('#message').focus(); 
    }); 


    /** 
    * Envois de message. 
    **/ 

    $('#form').submit(function(event){ 
     event.preventDefault(); 

     //Le serveur se souvient de l'utilisateur connecté sur ce socket, pas besoin de le define. 

     //Si le message n'est pas vide on envoie le message. 
     if($.trim($('#message').val()) != ''){ 
      socket.emit('newmsg', {message: $('#message').val()}); 
      $('#message').val(''); 
      $('#message').focus(); 
     } 
    }); 

    socket.on('newmsg', function(message){ 
     if (message.message.substr(0, 3) == "/w "){ 
      var destinataire_id = message.message.split(' ')[1]; 
      console.log(destinataire_id); 
      message.message = message.message.replace('/w ','').replace(destinataire_id,''); 
      socket.emit("private", { msg: message.message, dest: destinataire_id}); 

     }else{ 
      if (($('#messages')[0].scrollHeight - $('#messages').scrollTop()) == $('#messages').height()) 
      { 
       $('#messages').append('<div class="message">'+Mustache.render(msg, message)+'</div>'); 
       $('#messages').scrollTop($('#messages')[0].scrollHeight); 
      }else{ 
       $('#messages').append('<div class="message">'+Mustache.render(msg, message)+'</div>'); 
      } 
     } 

    }); 

    socket.on("private", function(data) {  
     $('#messages').append('<li class="private"><em><strong>'+ data.from +' -> '+ data.dest +'</strong>: '+ data.msg +'</em></li>'); 
    }) 


    /** 
    * Gestion des connectés. 
    **/ 
    socket.on('newuser', function(user){ 
     $('#users').append('<div id="'+ user.id +'" class="row one_user">'+ 
           '<div class="col-md-2 vcenter"><img src="'+ user.avatar +'"/></div>'+ 
           '<div class="col-md-9 vcenter">'+ user.username +'</div>'+ 
           '</div>' 
          ); 
    }) 

    socket.on('discuser', function(user){ 
     $('#' + user.id).remove(); 
    }) 


    /* socket.emit('send message', { 
     room: conversation_id, 
     message: $('#message_'+conversation_id) 
    }); */ 

})(jQuery); 

,如果你需要,我的html:

<!doctype html> 
<html> 
    <head> 
     <meta charset="utf-8"> 
     <link rel="stylesheet" href="css/bootstrap.min.css"> 
     <style>  

     #messages{ 
      min-height:300px; 
      overflow-y:auto; 
      max-height:600px; 
     } 

     #messages,#form{ 
      display:none; 
     } 

     .clear{ 
      clear:both; 
     } 

     .vcenter { 
      display: inline-block; 
      vertical-align: middle; 
      float: none; 
     } 

     .vtop { 
      display: inline-block; 
      vertical-align: top; 
      float: none; 
     } 

     .top-margin{ 
      margin-top:25px; 
     } 

     small{ 
      font-size:70%; 
     } 

     .message{ 
      margin:5px 0; 
     } 

     ::-webkit-scrollbar { 
      width: 12px; 
     } 

     ::-webkit-scrollbar-track { 
      -webkit-box-shadow: inset 0 0 6px rgba(214, 94, 0, 0.5); 
      border-radius: 5px; 
     } 

     ::-webkit-scrollbar-thumb { 
      border-radius: 5px; 
      -webkit-box-shadow: inset 0 0 6px rgba(214, 94, 0, 0.5); 
     } 

     #users>div{ 
      margin-top:10px; 
     } 

     </style> 
    </head> 
    <body> 
     <div class="container top-margin"> 
      <div class="col-md-9"> 
       <div class="row panel panel-default" id="messages"> 
       <ul class="nav nav-tabs"> 
        <li class="active"> 
         <a href="#"># All</a> 
        </li> 
       </ul> 
        <div class="message" id="msg" style="display:none;"> 
          <style> 
           .info_{{ user.username }} { 
            min-height: 50px; 
            position: relative; 
            -moz-border-radius: 10px; 
            -webkit-border-radius: 10px; 
            border-radius:   5px; 
            padding:8px; 
            background : {{ user.color }} 
           } 
           .info_{{ user.username }}:before { 
            content:""; 
            position: absolute; 
            right: 100%; 
            top: 10px; 
            width: 0; 
            height: 0; 
            border-top: 5px solid transparent; 
            border-bottom: 5px solid transparent; 
            border-right : 14px solid {{ user.color }} 
           } 
          </style> 
          <div style="text-align:center;" class="col-md-2 vtop"> 
           <img src="{{{user.avatar}}}" /> 
           <p><strong>{{user.username}}</strong></p> 
          </div> 
          <div class="info_{{ user.username }} col-md-9 vtop"> 
           {{message}} <br/> 
           <small>Posté à : {{h}}:{{m}}:{{s}}</small> 
          </div> 
        </div> 
       </div> 
       <form class="row" action="" id="form"> 
         <div class="col-md-12"> 
         <div class="input-group"> 
          <input id="message" type="text" class="form-control" placeholder="Type your text here..."> 
          <span class="input-group-btn"> 
           <button class="btn btn-default" type="submit">Envoyer</button> 
          </span> 
         </div> 
         </div>  
       </form> 
      </div> 
      <div class="col-md-3"> 
       <div class=" panel panel-default"> 
        <div class="panel-heading">Utilisateurs en ligne</div> 
        <div class="panel-body" id="users"></div> 
       </div> 
      </div> 
     </div> 
     <div id="login"> 
      <form action="" id="loginform"> 
       <h1>Bienvenue</h1> 
       <p>Veuillez vous connecter pour continuer.</p> 
       <input type="text" name="login" id="username" placeholder="Nom user"> 
       <input type="mail" name="mail" id="mail" placeholder="mail"> 
       <input type="submit" value="Envoyer"> 
      </form> 
     </div> 

     <script type="text/javascript" src="js/jquery.min.js"></script> 
     <script src="http://192.168.1.72:4120/socket.io/socket.io.js"></script> 
     <script src="js/mustache.min.js"></script> 
     <script src="js/bootstrap.min.js"></script> 
     <script type="text/javascript" src="js/client.js"></script> 
    </body> 
</html> 

如果你有一個關於我的私人信息如何工作的想法?

謝謝!

回答

0

最簡單的想法;將他們的用戶名和socket.id存儲在一個對象或另一個數據存儲中。

服務器端;

var users = {}; 

socket.on('login', function(user){ 
    // on connection store users, you can delete object properties on disconnect 
    users[user.username] = socket.id; // usernames and their socket ids are related now. 
}); 
socket.on('newmsg', function(message){ 
    if(message.indexOf('/w') == 0){ // Check, is user whispering 
     var messageArray = message.split(' '); // Split string as array 
     var username = messageArray[1]; // we got username 
     var msg = messageArray.splice(2).join(' '); // join message's words 
     socket.broadcast.to(users[username]).emit('newmsg', msg); // david gets message (users[username] gives his socket.id) 
    }else{ 
     // send message everybody 
    } 
}); 

因此,我們有最簡單的私人消息傳遞機制。

+0

工程就像一個魅力,謝謝你!我更瞭解socket如何工作! – WebFreak

+0

不錯,我剛剛注意到有一個錯誤的變量,我編輯它。 –