The chat tool, using Nodejs service, WebSocket front page, chat tool, can have any number of people to participate in the chat, inside the user ID for the analog ID.
First
Folder structure,
1. Install WS module, NPM install WS
2, Web.js file, is the Nodejs back-end code
var websocketserver = require (' ws '). SERVER,WSS = new Websocketserver ({port:8181});//var client1 = Null,client2=null,client1ready = False, Client2ready = FA Lse;var config = {};var userlist = {};wss.on (' connection ', function (WS) {Console.log (' client connected '); Ws.on (' message ', function (message) {var data = json.parse (message); Console.log (data); if (Data.type = = ' Register ') {console.log ("register"); Config[data.meid] = {Id:data.meid,mynike:data.sendnike,pipe:ws,ready:true}; Userlist[data.meid] = {Id:data.meid,mynike:data.sendnike}; Refreshlist (); }else if (Data.type = = ' SendMessage ') {console.log ("send"); SendMessage (data); }else{Ws.send (json.stringify ({"Error": true})); } }); Ws.on ("Close", function (code, reason) {for (var. config) {if (config[i].pipe = = = ws) {Config[i]. Ready = false; Config[i].pipe = null; Delete Config[i]; Delete Userlist[i]; RefreShlist (); Break }} console.log ("Close link"); }); });//Update the chat list function refreshlist () {for (var i in config) {config[i].pipe.send (json.stringify ({' type ': ' Refreshlist ', ' List ': UserList});}} Update chat function sendMessage (data) {if (Config[data.receiveid]) {//each other online data.sendnike = Userlist[data.meid].mynike; Config[data.meid].pipe.send (json.stringify (data)); Config[data.receiveid].pipe.send (json.stringify (data));} else{//the other party is not online config[data.meid].pipe.send (json.stringify ({"Error": true});}} NPM Install WS
2. Add Client client.html
<! DOCTYPE html>3, add the client, client2.html,client3.html,,, only need to modify the Client1.html, config Sendnick,
4. Be aware of adding jquery files
5. Nodejs start the Web.js file and open all. html files for chat.
Nodejs+websocket Chat Tool