Project needs, so I learned how to use node. js + socket. io to implement the private chat function. After busy working for a long time, I finally figured it out. The basic principle is that when the server receives
When a socket connects to the request, each socket will establish a socket, and the connected socket is not expressed, so each socket can only send information to itself.
The information sent to other socket connections must identify other socket connections.
Let's talk about the code ..
Server. js
var io = require('socket.io').listen(8080);io.set('log level', 1);var users = {};io.sockets.on('connection', function (socket) { io.sockets.emit('connect',{hell:'boy'}); socket.on('private message', function (from,to,msg) { console.log('I received a private message by ', from, ' say to ',to, msg);if(to in users){users[to].emit('to'+to,{mess:msg});} }); socket.on('new user',function(data){ if(data in users){ }else{var nickname = data;users[nickname]= socket; } console.info(users); }); socket.on('disconnect', function () { io.sockets.emit('user disconnected'); });});
Test page index.html
<Script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script> <script src = "http: // localhost: 8080/socket. io/socket. io. js "> </script> <script >$ (function () {var socket = io. connect ('HTTP: // localhost: 100'); socket. on ('connect ', function (data) {console. log (data) ;}); $ ("# send "). click (function (e) {var from = $ ('# user_name '). val (), msg = $ ('# message '). val (), to = $ ('# '). val (), $ message_list = $ ('# message_list'); socket. emit ('new user', from); socket. emit ('private message', from, to, msg); socket. on ('to' + from, function (data) {$ message_list.append ('
'+ Data. from +' + data. message +'') ;}) ;};}); </Script>Name:
Send:
Message content:Send
Project running effect:
Figure 2:
OK. Now you can chat privately...