页面重新加载节点Js和Socket.io时获取socket.id

时间:2015-11-10 04:25:31

标签: node.js socket.io

接近时间。我尝试使用节点Js和Socket.io编写聊天应用程序,我有1页login.html,1页chat.html和server.js文件。当我使用UserA登录时,我将发送电子邮件并传递给服务器并进行验证。之后,转到页面chat.html。在这里,我显示列表用户,但是当我尝试刷新页面chat.html时,socket.id发生了变化。我在数据库MongoDb中刷新后解压缩了socket.id,但是当我用UserB其他浏览器登录时,在UserA的刷新页面之后,但是UserB的socket.id发生了变化,而不是用户A.抱歉我的英文。

这是login.html页面

<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

      <body>
        <div class="container">
          <form class="form-signin" id="formLogin">
            <h2 class="form-signin-heading">Please sign in</h2>
            <label for="inputEmail" class="sr-only">Email address</label>
            <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus="">
            <label for="inputPassword" class="sr-only">Password</label>
            <input type="password" id="inputPassword" class="form-control" placeholder="Password" required="">
            <div class="checkbox">
              <label>
                <input type="checkbox" value="remember-me"> Remember me
              </label>
            </div>
            <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
          </form>
        </div> <!-- /container --> 
    <script type="text/javascript">
      jQuery(function ($){
        var socket= io.connect('http://localhost:8080');
        var $email =$('#inputEmail'),
            $password=$('#inputPassword'),
            $login=$('#formLogin');
        $login.submit(function (event){
          socket.emit('login', { email:$email.val(), password:$password.val()});
          socket.on('CheckLogin', function (data){
            console.log('show something');
            if(data){
              console.log(data);
              window.location.href='chat';
            }else {
              alert('Tai khoan hoac mat khau khong dung');
            }
          });
          /*  ,function (data){
              console.log(data);
              if(data){
                console.log('Login successfuly');
                window.location.href = "chat";
                socket.on('sendId', function(data){
                  console.log(data[0]._id);
                });
              }else {
                console.log('Login faile');
              }
          }*/
          event.preventDefault();
        });
      });
    </script>
  </body>
</html> 

这是server.js文件

var app = require('express')(),
                server = require('http').Server(app),
                io=require('socket.io')(server),
                mongoose=require('mongoose');

            server.listen(8080);
            var mongoURL = 'mongodb://localhost/ChatDatabase';
            app.get('/login', function(req, res){
                res.sendFile(__dirname+'/signin.html');
            });


            var  emailprecentLogin='';      
            var namePreLogin = '';
            var logInStatus = false; 
            var Users= mongoose.model('Users',{
                email :String, 
                name:String,
                password:String, 
                socketId :String
            });

            var Messages = mongoose.model('Messages',{
                name :String, 
                message:String 
            });

            /*list variable*/
            var mailLogin =  '';
            var statusLogin = false ; 
            var listLogin =[];
            mongoose.connect(mongoURL , function(err, db){
                if(err){
                    console.log('Connect err');
                }else {
                    console.log('Connect successfuly');

                    /*get value send from loginform and verify*/
                    io.on('connection', function (socket){  
                        socket.on('login', function (data){
                            var tmpEmail = data.email ; 
                            var tmpPass= data.password ; 
                            mailLogin = data.email;
                            console.log('info login' + tmpEmail + tmpPass);
                            Users.findOne({ email:tmpEmail, password:tmpPass }).exec(function(err , docs){
                                if(docs==null){
                                    console.log(err +typeof(docs));
                                    socket.emit('CheckLogin', false);
                                }else {
                                    if(docs.email == tmpEmail && docs.password==tmpPass){
                                        statusLogin=true;
                                        socket.emit('CheckLogin', true);
                                        console.log('Info of user login:'+docs + typeof(docs));
                                        app.get('/chat', function (req, res){
                                            res.sendFile(__dirname+'/chat.html');
                                        }); 
                                    }
                                }
                            });
                        });/*end verify login*/


                        socket.emit('tmpEmailLogin',mailLogin );

                        /*update socket id when user f5 or refresh page*/
                        socket.on('connectServer', function(data){
                            /*console.log(data);*/
                            console.log('User F5'+data);
                            var tmpSocketId = socket.id ;
                            var tmpLogin = data;
                            Users.update({email:data},{$set:{socketId:tmpSocketId}},function (err, userUpdate){
                                if(err){
                                    /*console.log(err);*/
                                    console.log("err sendSocketID");
                                }else {
                                    Users.find({}).exec(function(err, docs){
                                        if(err){
                                            console.log('Err find list user');
                                        }else {
                                            socket.emit('listUser', docs);
                                        }
                                    });
                                    Users.find({email:mailLogin}).exec(function(err, docs){
                                        if(err){
                                            console.log('Err find list user');
                                        }else {
                                            console.log('Updated socketId');
                                            /*console.log(docs);*/
                                        }
                                    });
                                }
                            });

                        });


            /*update socket when user click item*/          
                        socket.on('updateSocketId', function(data){
                            Console.log('user f5 :' + mailLogin);
                        });


                    });
                }
            });

这是chat.html文件

<!DOCTYPE html>
    <!-- saved from url=(0040)http://getbootstrap.com/examples/signin/ -->
    <html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
        <meta name="description" content="">
        <meta name="author" content="">
        <link rel="icon" href="http://getbootstrap.com/favicon.ico">
        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" >

        <!-- Optional theme -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" >
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
        <title>Chat</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script src="/socket.io/socket.io.js"></script>
        <style type="text/css">
        #viewContent{
          color: black ; 
          height: 400px;
          background-color: #F5F5F5;
          overflow: scroll;
        }
        #listUser{
          height: 400px;

        }
        </style>
      </head>

      <body>

        <div id='header'>
          <h2 class="title">This is chat box</h2>
        </div>

        <div id='content' >
          <div id='listUser' class='col-md-4'>
            <li  id ='list' class = "list-group-item active">List User</li>
          </div>

          <div name='chatbox' class='col-md-8'>
            <li  id ='yourname' class = "list-group-item active">Your Name</li>
            <div id='viewContent'></div>

            <div name='formInput'  >
              <form class='' id='formChat'>
                <div class="form-group">
                  <label class="sr-only" for="contentChat">Enter message</label>
                  <input type="text" class="form-control" id="contentChat" placeholder="Enter message" />
                  <input type='submit' class='btn btn-primary ' value ='Send'/>
                </div>
              </form>
            </div>

          </div> <!-- chat box div -->
        </div>

        <script type="text/javascript">
          jQuery(function($){        
            var socket = io.connect('http://localhost:8080');
            var $contentChat = $('#contentChat'),
                $send =$('formChat');
            var tmpEmailLogin;
            var listID = [];
            var idSocket='' ;
            var emailPre= '';/*user login precent*/
            var tenLogin ='';
            var value_id ='';
            /*<----------- chat 
            send list user form server
            set connect 2 user
            show message
            ------------->*/
            /*   socket.on('infoLogin', function(docs){
                emailPre=docs ;
              });*/


            /*send list user */

            socket.on('tmpEmailLogin', function(data){
              tmpEmailLogin = data;
              /*console.log(data);*/
              socket.emit('connectServer',tmpEmailLogin); /*gửi socket để set socketId lên database*/
            });
            /*console.log('user login :' +tmpEmailLogin);*/

            socket.on('listUser', function(data){/* show list user in database*/
              console.log('socketId listUser :' + socket.id);
              var j = 0 ; 
              /*console.log('Email login:' +emailPre);*/
              $('#listUser').empty();
              for(var i =0 ; i<data.length; i++){
               $('#listUser').append('<a href ="#" id="'+ data[i].email+'" class="list-group-item" value="'+data[i].socketId+'">' +data[i].name+ '</a>');
              }
            });

            var click = 0 ;  
            $(document).on('click', 'a.list-group-item', function(event){
              click ++; 
              $('#viewContent').innerHTML='';
              if(click =1){
                $('a.list-group-item').each(function(i , obj){
                  this.setAttribute("class", " list-group-item");
                  click = 0 ;
                  $('#viewContent').empty();
                }); 
              }
              /*emailLogin=this.id;*/
              var reqIdOfEmail = this.id;
              this.setAttribute("class", " list-group-item active");
              socket.emit('updateSocketId', reqIdOfEmail);
              socket.on('ResSocket', function (data){
                idSocket = data.idSk;
                nameOfSk  = data.nameReq ; 
                console.log(nameOfSk+idSocket );
              });
              event.preventDefault();
            }); /* end click*/


            $('#formChat').submit(function(event){
              var $contentMsg = $('#contentChat').val();
               /*alert($contentMsg);*/
              if(idSocket!=''&& idSocket!=null){
                socket.emit('SendMsg', {idsocket:idSocket, msg:$contentMsg, name:tenLogin})
              }
              event.preventDefault();
            });


            /*P2P message*/
            socket.on('P2Pmessage', function (data){
              /*var nameReq= data.name;*/
              console.log('show something here');
              var msgContent=data.content;

              $('#viewContent').append('<b></b>'+msgContent +'<br>' );
            }); 

          });
        </script>

      </body>
    </html>

1 个答案:

答案 0 :(得分:2)

您可以将您的用户加入同一个房间, 所以即使socketId会改变 他们可以发送和接收消息。

您可以通过此代码加入会议室:

io.on('connection', function(socket){
      socket.join('some room');
});

并向房间发送消息:

io.to('some room').emit('some event'):

您可以找到更多文档here