简体   繁体   中英

sockets.io - How to detect user typing in an input form and broadcast to all users

I have this function on client side (modified):

 var textarea = $('#textarea'); var typingStatus = document.querySelector('#typing_on'); var lastTypedTime = new Date(0); var typingDelayMillis = 500; function refreshTypingStatus() { if (!textarea.is(':focus') || textarea.val() == '' || new Date().getTime() - lastTypedTime.getTime() > typingDelayMillis) { socket.emit('type' , typingStatus.innerHTML = 'No') } else { socket.emit('type' , typingStatus.innerHTML = 'Typing...') } } function updateLastTypedTime() { lastTypedTime = new Date(); } setInterval(refreshTypingStatus, 100); textarea.keypress(updateLastTypedTime); textarea.blur(refreshTypingStatus);

 <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="styles.css"> <link rel="stylesheet" type="text/css" href="styles2.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <input name="textarea" id="textarea" cols="45" rows="5"> <div id="typing_on"></div> </body>

i did the necessary code in the server side as well but i think it doesn't work cause its under io.on(connection,function(socket)) but there is no way to detect input or typing condition on server side.

it doesn't work for other clients and only appears for the same user

Is there any alternative i can use to make it work?

References:

<input name="textarea" id="textarea" cols="45" rows="5" onchange="sendTypingStatus()">

FrontEnd - Javascript : Emitting typing event and listening getTypingStatus for showing 'typing..' on dom

  • Emit event typing as user types using socket.emit
  • Listen to getTypingStatus message to show 'typing..' using socket.on
function sendTypingStatus() {
socket.emit('typing')
}

socket.on('getTypingStatus',message => {
  handleShowingTypingStatusOnDOM()
})

Server Side : Listen typing event and Broadcast to All users except socket that is broadcasting the message using socket.broadcast

io.on('connection', (socket) => {
  socket.on('typing',(message)=>{
  socket.broadcast.emit('getTypingStatus', 'typing!');
 }
})

socket.broadcast will broadcast message to all users those are connected inside io() connection

socket.emit('type', typingStatus.innerHTML = 'No') does not execute typingStatus.innerHTML = 'No' on the other clients. In order to do that you need to be able to handle an incoming type event packet on the other clients.

Also, use an event handler on the focus and blur events instead of polling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM