Sunday, 2 April 2017

Trying to send message private in room,but it not work

I'm trying to do chat private with socket.io node js.There are code in server when user login to room.

    socket.on('add user', function (username) {
    if (addedUser) return;

    // we store the username in the socket session for this client
    socket.username = username;
    users.push(socket.username);
    socket.join('room1');
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers: numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.emit('user joined', {
      username: socket.username,
      numUsers: numUsers,
      arrayUser : users
    });
  });

My code in client:

    function sendMessage () {
    var message = $inputMessage.val();
    // Prevent markup from being injected into the message
    message = cleanInput(message);
    // if there is a non-empty message and a socket connection
    if (message && connected) {
      $inputMessage.val('');
      addChatMessage({
        username: username,
        message: message
      });
      // tell server to execute 'new message' and send along one parameter
      socket.emit('new message', message);
    }
  }

after send message from client,my server get data from client send in room,there is my code in server

    socket.on('new message', function (data) {
    // we tell the client to execute 'new message'
    /*socket.broadcast.emit('new message', {
      username: socket.username,
      message: data
    });*/
    io.sockets.in('room1').emit('new message',data);
    console.log(data);
  });



via Huỳnh Trọng Nhân

No comments:

Post a Comment