Userlist is not being updated

25 views
Skip to first unread message

Hayk Safaryan

unread,
Aug 4, 2016, 10:39:27 AM8/4/16
to nodejs
first of all I am total noob to NodeJS, and mostly new to the backend. So I am learning them by creating a chat application. I've already integrated many features but cannot implement the update of users in the user list. I'm using socket.io for this. Here is my socket.js file.

    module.exports = function (io,rooms) {
      var chatrooms = io.of('/roomlist').on('connection', function(socket) {
        console.log('Connection Established on the server');
        socket.emit('roomupdate',JSON.stringify(rooms));
        socket.on('newroom',  function(data) {
          rooms.push(data);
          socket.broadcast.emit('roomupdate',JSON.stringify(rooms));
          socket.emit('roomupdate',JSON.stringify(rooms));
        });
      });
      var messages = io.of('/messages').on("connection", function(socket) {
        console.log('connected to the chatroom!');
        socket.on('joinroom', function(data) {
          socket.username = data.user;
          socket.userPic = data.userPic;
          socket.join(data.room);
          updateUsersList(data.room,true);
        });
        socket.on('newMessage', function(data) {
          socket.broadcast.to(data.room_number).emit('messagefeed', JSON.stringify(data));
        });
        function updateUsersList(room, updateALL) {
          // var getUsers = io.of('/messages').clients(room); OLD VERSION
          var getUsers = io.of('/messages').in(room).clients;
          var userlist = [];
          for (var i in getUsers) {
            userlist.push({user:getUsers[i].username, userPic:getUsers[i].userPic});
          }
          socket.to(room).emit('updateUsersList',JSON.stringify(userlist));
          if (updateALL) {
            socket.broadcast.to(room).emit('updateUsersList', JSON.stringify(userlist));
          }
        }
        socket.on('updateList', function(data) {
          updateUsersList(data.room);
          console.log('updateList triggered in socket.js');
        });
      });
    };

And this is my room page

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>ChatCAT</title>
        <link rel="stylesheet" href="../css/normalize.css" media="screen" title="no title" charset="utf-8">
        <link rel="stylesheet" href="../css/room.css" media="screen" title="no title" charset="utf-8">
        <script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
        <script src="/socket.io/socket.io.js" charset="utf-8"></script>
        <script type="text/javascript">
          $(function functionName() {
            var host = "{{config.host}}";
            var messages = io.connect(host + "/messages");
            var roomNum = "{{room_number}}";
            var userName = "{{user.fullname}}";
            var userPic = '{{user.profilePic}}';
    
            messages.on('connect', function(event) {
              console.log('Connection Established');
              messages.emit('joinroom', {room:roomNum, user:userName, userPic:userPic})
            })
            $(document).on('keyup', '.newmessage', function(event) {
              if (event.which === 13 && $(this).val()!='') {
                messages.emit('newMessage', {
                  room_number:roomNum,
                  user:userName,
                  userPic:userPic,
                  message:$(this).val()
                })
                updateMessageFeed(userPic, $(this).val());
                $(this).val('');
              }
            })
    
            messages.on('messagefeed', function(data) {
              var msgs = JSON.parse(data);
              updateMessageFeed(msgs.userPic, msgs.message);
            })
    
            function updateMessageFeed(userPic, message) {
              var str = "<li>";
                str +='<div class="msgbox">';
                  str +='<div class="pic">';
                    str +='<img src="'+ userPic +'" />';
                  str +='</div>';
                  str +='<div class="msg">';
                    str +='<p>';
                      str +=message;
                    str +='</p>';
                  str +='</div>';
                str +='</div>';
              str +='</li>';
              $(str).hide().prependTo($('.message')).slideDown(100, function() {
                //Stuff to do *after* the animation takes place
              });
              console.log(str);
            }
            messages.on('updateUsersList', function(data) {
              var userlist = JSON.parse(data);
              $('.users').html('');
              for (var i = 0; i < userlist.length; i++) {
                // userlist[i]
                var str = '<li><img src="'+ userlist[i].userPic +'" /><h5>'+ userlist[i].user +'</h5></li>';
    
                $(str).prependTo($('.users'));
              }
              console.log(str);
            })
            setInterval(function () {
              messages.emit('updateList',{room:roomNum});
              console.log('interval');
            }, 15*1000)
          });
        </script>
      </head>
      <body>
        <div class="rm-container">
          <h1 class="rm-title">ChatCAT</h1>
          <div class="rm-userbox">
            <img src="{{user.profilePic}}" class="userPic" />
            <h3 class="userName">{{user.fullname}} | <a href="/logout">Logout</a> <a href="/chatrooms">More Chatrooms</a></h3>
          </div>
          <div class="rm-roomname">
            <h5>{{room_name}}</h5>
          </div>
          <div class="rm-message">
            <ul class="message">
    
            </ul>
          </div>
          <div class="rm-users">
            <ul class="users">
    
            </ul>
          </div>
          <div class="rm-newmessage">
            <input type="text" class="newmessage" autocomplete="off" placeholder="Type in your message and press enter!">
          </div>
        </div>
      </body>
    </html>


Also here is the github repository for my project. https://github.com/hayk94/ChatCat
And the commit of this functionality.


EDIT: 
After adding some cons logs it seems that the problem is in these lines of code in socket.js
`function updateUsersList(room, updateALL) {
      // var getUsers = io.of('/messages').clients(room); OLD VERSION
      var getUsers = io.of('/messages').in(room).clients;
      var userlist = [];
      for (var i in getUsers) {
        userlist.push({user:getUsers[i].username, userPic:getUsers[i].userPic});
      }
      socket.to(room).emit('updateUsersList',JSON.stringify(userlist));
      if (updateALL) {
        socket.broadcast.to(room).emit('updateUsersList', JSON.stringify(userlist));
        console.log('updateALL triggered');
      }
      console.log('updateUsersList function triggered');
    }`

The emit and the broadcast seems to not work. As in the room.html

`messages.on('updateUsersList', function(data) {
          console.log('messages.on updateUsersList');
          var userlist = JSON.parse(data);
          $('.users').html('');
          for (var i = 0; i < userlist.length; i++) {
            // userlist[i]
            var str = '<li><img src="'+ userlist[i].userPic +'" /><h5>'+ userlist[i].user +'</h5></li>';
            console.log(str);
            $(str).prependTo($('.users'));
          }
          console.log(str);
        })`
The updateUsersList is not being triggered.
Reply all
Reply to author
Forward
0 new messages