Show all users the letter that is pressed with socket.io

1

What should I use in socket.io and node.js to see in real time when a user presses any key? Up to now I have been sending messages to all users through a button that triggers an event, now I would like to make the event is issued every time a key is pressed without the need for a button that emits the event.

    
asked by Sergio Diaz 14.03.2017 в 01:30
source

2 answers

1

Server

First, you must configure your SocketIO server:

let server = /* puede ser express, koa, o vanilla Node.js */
let socket = io(server);
let connectedUsers = {};

socket.on('connection', socket => {
  connectedUsers[socket.id] = { letters: [] };
});

socket.on('key', ({ id, key } => {
  connectedUsers[id].letters.push(key);
  console.log('El usuario ${id} ha pulsado ${key}');
});

Client

On the client side, you must do two things:

  • Listen to the server.
  • Add a handler for the event keypress of the element to listen to.
  • Send the user id in each broadcast.
  • First we listen to the server:

    let socket = io('//localhost:9000');
    

    Next, we add a handler for the event keypress of the element that will be listened to.

    let input = document.getElementById('source');
    input.addEventListener('keypress', send);
    

    Finally, we send the typed letter along with the client id:

    function send (e) {
      socket.emit('key', { id: socket.id, key: e.key });
    }
    

    Each time a letter is written, the server will print the following:

      

    The user "customer id" has pressed "letter"

        
    answered by 14.03.2017 в 02:11
    0

    To know which key was pressed on the client side you can do this:

    $(document).ready(function(){
      
       $(document).keypress(function (e){
        var pressedKey = String.fromCharCode(e.which);
        console.log('Tecla presionada: ' + pressedKey);
       });
      
    });
    input{
      width: 100%;
      height: 30px;
      font-family: Arial;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" placeholder="Escribe un mensaje..." />

    Already to send and receive it by means of your emit and on respectively, you can simply do the following:

    Client side

    $(document).ready(function(){
      
       $(document).keypress(function (e){
        var pressedKey = String.fromCharCode(e.which);
        // Aquí hacemos nuestro emit y envíamos la tecla presionada
        // al lado del servidor... :D !
        socket.emit('pressedKey', {'pressedKey': pressedKey});
       });
      
    });

    Server side

    io.on('connection', function (socket) {
        // Aquí recibimos nuestra tecla presionada en el lado del servidor
        socket.on('pressedKey', function (data) {
            console.log('Tecla presionada: ' + data.pressedKey);
        });
    });
    
        
    answered by 14.03.2017 в 01:49