I recently made a chat for a client, so I used NodeJS to make one
The principle is that after the user enters for the first time, record its ID and the user's ws
When someone sends data, check the ID, then find the ws corresponding to the ID, and send the message
The core is to use an array to make a python dictionary-like thing
var WebSocketServer = require('ws').Server, wss = new WebSocketServer({ port: 8888 }); var AllUserData = new Array(); 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(var i=0;i<AllUserData.length;i++) { if(Temp.ID == AllUserData[i]['id']) { if(Temp.Data != "userregister") { AllUserData[i]['ws'].send(Temp.ID+Temp.Data); break; } } } } }); }); function CheckIsNew(Temp) { for(var i=0;i<AllUserData.length;i++) { if(Temp.ID == AllUserData[i]['id']) { return false; } } return true; }
The following is a simple connection Demo
<html> <head> <title>GetData</title> </head> <body> <textarea cols=40 rows=20 id="output"></textarea> <button width=200 height=200 onclick="Sent(2,111)">Sent1</button> <button width=200 heigh=200 onclick="Sent(1,222)">Sent2</button> </body> <script src="https://www.gstatic.com/firebasejs/4.13.0/firebase.js"></script> <script src="websocket.js"></script> <script> var s= new MyWebSocket(success,fial,getmes); s.OPen("ws://127.0.0.1:8888"); register(1); register(2); function Sent(friendid,Data) { var Json = { 'ID':friendid, 'Data':Data }; s.Sent(JSON.stringify(Json)); } function register(id) { var Json = { 'ID':id, 'Data':"userregister" }; s.Sent(JSON.stringify(Json)); } function start() { } function success() { document.getElementById("output").value = "success"; } function fial(a) { } function getmes(a) { document.getElementById("output").value = a; } </script> </html>
The websocket.js used in it can be seen in my previous blog, of course, you can also write it yourself