Socket.io how to check if user is typing and broad

2019-03-17 02:22发布

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 know i can emit when some is typing from client to server, I can also broadcast it to other users. But will it be efficient to do that on every keyup? How do i handle such situation? Below is my code for now:

$("#textbox").keyup(function (e)  {
 if (e.keyCode == 13)  {
  socket.emit('send', {nickname: $('#nickname').val() , msg: $("#textbox").val()});
      $('#textbox').val('');  }
 else{
  socket.emit('is typing',  {nickname: $('#nickname').val()});
     }
});

and on server side:

socket.on('is typing', function(data){
 socket.broadcast.emit('typing', {nickname: data.nickname});
});

4条回答
劳资没心,怎么记你
2楼-- · 2019-03-17 02:45

You can use timeouts to send "started typing" and "stopped typing" messages, like so:

var typing = false;
var timeout = undefined;

function timeoutFunction(){
  typing = false;
  socket.emit(noLongerTypingMessage);
}

function onKeyDownNotEnter(){
  if(typing == false) {
    typing = true
    socket.emit(typingMessage);
    timeout = setTimeout(timeoutFunction, 5000);
  } else {
    clearTimeout(timeout);
    timeout = setTimeout(timeoutFunction, 5000);
  }

}

It's rough, but you should get the idea.

查看更多
你好瞎i
3楼-- · 2019-03-17 02:48

Just thought I'd add my variation on the very helpful answer given by abject_error. This allows for the status of typing as well as stopped typing but message was entered. I'm not using socket.io but you get the idea.

var typingStatus=0; //0=Not typing: message blank, 1=typing, 2=typing: something there
var typingStatus_timeout = undefined;

//called when timeout kicks in that we've stopped typing
function function_typingStatus_timeout(){
    //message entered
    if ($('#chat_message').val().trim()) {
        typingStatus=2;
    //message is blank
    } else {
        typingStatus=0;
    }
    //send new status
    connection.send(JSON.stringify({
        action:'typingStatus',
        typingStatus:typingStatus,
    }));
}

$(document).ready(function(){
    //TYPING
    $('#chat_message').keydown(function(e) {
        //only record typing if enter not pressed
        if(e.which!=13 && e.keyCode!=13) {
            //weren't typing before but are now
            if (typingStatus!=1) {
                //switch to 1 for in progress
                typingStatus=1;
                //broadcast
                connection.send(JSON.stringify({
                    action:'typingStatus',
                    typingStatus:typingStatus,
                }));        
            //were typing before and still are, clear the timeout, we're going to reset it in the next step
            } else {
                clearTimeout(typingStatus_timeout);
            }
            //either way, set the timeout to trigger after a second of not typing
            typingStatus_timeout=setTimeout(function_typingStatus_timeout,1000);

        //if enter was pressed we want to not have it register as a keydown at all.  there's a separate function on keyup that looks for enter being pressed and sends the message
        } else {
            e.preventDefault();
        }
    });
});
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-03-17 03:02
   function typingtimeoutFunction (){                 

      socket.emit('typingMessage', 'stopped typing');    
    },

    onKeyDownNotEnter: function (){
         clearTimeout(this.typingtimeout);
         socket.emit('typingMessage', 'istyping');
        this.typingtimeout = setTimeout(function() {ajaxChat.typingtimeoutFunction();}, 5000);      
    },
查看更多
\"骚年 ilove
5楼-- · 2019-03-17 03:04

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 += '<p><strong>' + data.handle + ': </strong>' + data.message + '</p>';
});

socket.on('typing', function(data){
    if (data) {
      feedback.innerHTML = '<p><em>' + data + ' is typing...</em></p>';
    } else {
      feedback.innerHTML = ''
    }
});

Note how it doesn't need the typing boolean variable

查看更多
登录 后发表回答