socket.broadcast.to(id).emit()不起作用,但socket.broadcast确实

时间:2017-05-03 20:29:06

标签: jquery node.js sockets

我是nodeJS的新手,我正在尝试构建聊天应用程序。我的想法是,当用户点击名称时,他将能够与该用户聊天。 我使用MongoDB来保持用户'由socket.id提供的名称和ID。 这是我的代码:

文件index.html位于' public'。

目录中

index.html,函数start()在jquery之外,因为它不想那样工作。

<!DOCTYPE html>
<html lang="en">
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
  <script src="/socket.io/socket.io.js"></script>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
  <link href="/favicon.ico" type="image/x-icon" rel="icon" />

</head>
<body>
  <h1>Tchat</h1>
  <div class="inscrire">
    <form action="" id="form">
     <input type="text" placeholder="Enter your name" id="username">
     <input type="submit">
     </form>
  </div>

  <div id="container">

  <div id="userList">

  </div>

    <div class="chat" id="chat">
       <div class="chatHeader" id="chatHeader"></div>
       <div class="messages"> </div>
     <div>
       <form action="" id="send">
       <textarea name="name" rows="8" cols="80" id="message"></textarea>
       <input type="submit" value="envoyer">
       </form>
     </div>

    </div>


  </div>
<script>
var socket = io();

var $currentUser;

function start(id, name){
  document.getElementById("chat").style.display = "block";
  document.getElementById("chatHeader").innerHTML = name;
  socket.emit('startchat', id, $currentUser);
}


$(document).ready(function(){
  $('#container').hide();

//partie users
  function username(){
    var username = $("#username").val();

    if(username !== ''){
        $currentUser = username;
        socket.emit('new user',{user: username});
        $("#username").val('');
        $('#form').hide();
        return true;
      }
     else{
       return false;
    }

    }

 $('.inscrire').submit(function(event){
  event.preventDefault(); 
      if(username()){
     $('#container').show();
     $('.chat').hide();
   }

 });

//display users
 socket.on('userName', function(data){
   for(var i = 0; i < data.length; i++){
     if(data[i].name != $currentUser){
       $('#userList').append('<li onClick="start(\'' + data[i].socketId + '\''+','+'\'' + data[i].name + '\')">'+ data[i].name + '</li>');
       }
   }
 });


//msg part
 $('#send').submit(function(event){
   event.preventDefault();
   var msg = $("#message").val();
   socket.emit('message',msg);
   $("#message").val('');
 });

socket.on('msg', function(data){
  alert(data);
});
});

</script>



</body>
</html>

server.js

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io').listen(http);

var mongo = require('mongodb').MongoClient;


app.use(express.static('public'));

mongo.connect('mongodb://127.0.0.1/chat', function(err,db){
  if(err) throw err;
  console.log('connected to database');

  io.on('connection', function(socket){
    socket.on('new user', function(data){
      db.collection('users').find({"name":data.user}).count().then(function(numItems) { //to avoid the Promise<spending> mistake
      if(numItems == 0){
           db.collection('users').insertOne(
             {"name": data.user,
              "socketId": socket.id}
           );
           console.log('data inserted');
           callback();
         }
         else{
           console.log('data already inserted');
           callback();
         }

      });
      //envoyer le nom du user pour l'afficher
      db.collection('users').find().toArray(function(err,res){
        if(err) throw err;
        socket.emit('userName', res);
      });

    });
//partie msg

socket.on('startchat', function(id, name){
    socket.on('message', function(data){
    console.log(data);
    socket.broadcast.to(id).emit('msg', data);

  });
});


  });



});





http.listen('3000', function(){
  console.log('server is listening on port 3000');
});

我希望用户在其他用户发送消息时收到提醒,但这并不起作用。如果我使用socket.broadcast.emit(&#39; msg&#39;,数据),并使用socket.broadcast.to(id).emit(&#39; msg&#39;,data),那就不是&# 39;也可以。我做错了什么?

0 个答案:

没有答案