Thursday, 25 May 2017

Socket.io communication between clients like chatting only with ones' self

I am writing a chat system. I have the following on the client side:

<div id="messages-div"><div id="messages-inner-div"><ul id="messages"></ul></div></div>
<form id="messenger">
  <input id="m" autocomplete="off" placeholder="type something..." /><button id="send-message" class="fa fa-paper-plane"></button>
</form>
<script>

  $(function () {

    var user = '<%= user%>';
    popGroupList();
    var q = param();
    console.log(q);
    user = user.split('@');
    //~ alert(q.user[0]);
      if(user[0] == q.user[0]){
        user = '<span class="blue">'+user[0]+'</span>';
      } else {

        user = user[0];
        location.href='/messenger?user='+user;
      }      
    var socket = io();
    $('form').submit(function(){
      //~ console.log($('#m').val());
      socket.emit('chat',$('#m').val());//send the message
      $('#m').val('');//empty the input box
      return false;//prevent submitting the form
    });
    socket.on('chat', function(msg){
      d = formattedDate();
      $('#messages').prepend($('<li>').html('<b>('+d+') '+user+'</b>: '+msg));
    });
  });
</script>

and the following on the server:

var user = req.session_state.user;
            var io = require('socket.io').listen(server);
            io.on('connection', function(socket){
                console.log(req.session_state.user +' has connected');
                socket.join('room');                    
                socket.emit('chat', 'You are now connected, '+user);
                socket.on('chat',function(msg){

                    io.to('room').emit('chat', msg);
                    console.log(user +' said '+msg);
                });
                socket.on('disconnect', function(){
                    console.log(user +' has disconnected');
                });
            });

The problem I am facing is when I hit enter after writing a message, only I get the message I sent. I am running the latest (2.x) version of socket.io and node.js version 7.x

I have seen a lot of tutorials that use io.sockets.emit - but they are all old and I don't see that in the docs anymore.

I appreciate any help you can give.



via phpmydev

No comments:

Post a Comment