Socket.io how to check if user is typing and broadcast it to other users

后端 未结 4 466

I am trying to setup socket.io chat server. I have gotten it up to send and receive message from server and client. I was interested in showing users if some one is typing. I kn

4条回答
  •  猫巷女王i
    2021-02-02 03:21

    Just adding my code here following this tutorial: https://www.youtube.com/watch?v=FvArk8-qgCk&index=5&list=PL4cUxeGkcC9i4V-_ZVwLmOusj8YAUhj_9

    // Make connection
    var socket = io.connect('http://localhost:4000');
    var timeout
    // Query DOM
    var message = document.getElementById('message'),
          handle = document.getElementById('handle'),
          btn = document.getElementById('send'),
          output = document.getElementById('output'),
          feedback = document.getElementById('feedback');
    
    // Emit events
    btn.addEventListener('click', function(){
        socket.emit('chat', {
            message: message.value,
            handle: handle.value
        });
        message.value = "";
    });
    
    function timeoutFunction() {
      socket.emit("typing", false);
    }
    
    message.addEventListener('keyup',function(){
     socket.emit('typing', handle.value);
     clearTimeout(timeout)
     timeout = setTimeout(timeoutFunction, 2000)
    })
    
    
    // Listen for events
    socket.on('chat', function(data){
        feedback.innerHTML = '';
        output.innerHTML += '

    ' + data.handle + ': ' + data.message + '

    '; }); socket.on('typing', function(data){ if (data) { feedback.innerHTML = '

    ' + data + ' is typing...

    '; } else { feedback.innerHTML = '' } });

    Note how it doesn't need the typing boolean variable

提交回复
热议问题