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"