I write a small chat on node.js. Now chat is shared. When sending a message to the chat, it appears in all users. How to implement the ability to send messages to a specific user?
index.js
var app = require('express')(); var http = require('http').Server(app); let io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); http.listen(3000, function(){ console.log('3000 is run'); }); io.on('connection', function(socket){ console.log('new client here'); socket.on('message', function(data){ console.log(data); }) }); index.html
<!DOCTYPE html> <html> <head> <title>Chat</title> </head> <body> <textarea id="message"></textarea> <button id="send">Send</button> </body> <script src="socket.io/socket.io.js"></script> <script type="text/javascript"> var socket = io('http://localhost:3000/'); document.querySelector('#send') .addEventListener('click', ev => { ev.preventDefault(); let text = document.querySelector('#message').value; socket.emit('message', text); }) </script> </html>
socketId, so emit needs to be sent to him and not to all -io.sockets.connected[socketid].emit(...);. Most likely you can hook it up to the socket here -io.on('connection', function(socket)- Artem Gorlachev