Recently gave a customer a chat, so he made a nodejs with a
The principle is that after the user first enters, record its ID and the user's WS
When someone sends the data, look for the ID, then find the WS for the ID, send the message.
The core is to do something like a python dictionary with an array.
varWebsocketserver = require (' WS '). Server,wss=NewWebsocketserver ({port:8888 });varAlluserdata =NewArray (); Wss.on (' Connection ',function(WS) {Console.log (' Client Connected '); Ws.on (' Message ',function(message) {console.log (message); Temp=json.parse (message); if(Checkisnew (Temp)) {Alluserdata.push ({' ID ': Temp.id,' WS ': ws}); Console.log (Alluserdata); } Else { for(vari=0;i<alluserdata.length;i++) { if(temp.id = = alluserdata[i][' ID ')]) { if(Temp.data! = "Userregister") {alluserdata[i][' WS '].send (temp.id+temp.data); Break; } } } } });});functioncheckisnew (Temp) { for(vari=0;i<alluserdata.length;i++) { if(temp.id = = alluserdata[i][' ID ')]) { return false; } } return true;}
Here is a simple link to Demo
<HTML> <Head> <title>GetData</title> </Head> <Body> <textareacols=40rows=20ID= "Output"></textarea> <Buttonwidth=200Height=200onclick= "Sent (2,111)">Sent1</Button> <Buttonwidth=200Heigh=200onclick= "Sent (1,222)">Sent2</Button> </Body> <Scriptsrc= "Https://www.gstatic.com/firebasejs/4.13.0/firebase.js"></Script> <Scriptsrc= "Websocket.js"></Script> <Script> vars= NewMywebsocket (success,fial,getmes); S.open ("ws://127.0.0.1:8888"); Register (1); Register (2); functionSent (friendid,data) {varJson= { 'ID': friendID,'Data':D ATA}; S.sent (Json.stringify (JSON)); } functionRegister (ID) {varJson= { 'ID': ID,'Data':"Userregister" }; S.sent (Json.stringify (JSON)); } functionstart () {}functionsuccess () {document.getElementById ("Output"). Value= "Success"; } functionFial (a) {}functionGetmes (a) {document.getElementById ("Output"). Value=A; } </Script></HTML>
Inside the websocket.js, you can look at my front of the blog, of course, can also directly write their own
[NodeJS] Nodejs Multi-user point-to-point instant Messenger chat based on WebSocket