Server code (dependent on KOA2, koa-websocket)
/*instantiating external dependencies*/Let Koa= Require ("KOA2"); let WebSocket= Require ("Koa-websocket");/*instantiate the WebSocket, instantiate and store all the on-line text arrays and assign the listening ports*/Let app= WebSocket (NewKoa ()); let Ctxs=[];app.listen (80);/*implement a simple send message*/App.ws.use (CTX, next)={Ctxs.push (CTX); Ctx.websocket.on ("Message", (message) = ={console.log (message); for(Let i = 0; i < ctxs.length; i++) { if(CTX = = Ctxs[i])Continue; Ctxs[i].websocket.send (message); } });});
Front-end Code (this page can open more than one chat at a time)
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title>Title</title></Head><Body> <inputtype= "text"ID= "Content" /> <inputtype= "button"value= "Send"ID= "Send" /></Body><Scripttype= "Text/javascript"> /*encapsulating methods for WebSocket instantiation*/ varCreatewebsocket= (function () { return function(urlvalue) {if(window. WebSocket)return NewWebSocket (Urlvalue); if(window. Mozwebsocket)return NewMozwebsocket (Urlvalue); return false; } })(); /*instantiate a WebSocket connection object with the Address WS protocol*/ varWebSocket=Createwebsocket ("Ws://localhost"); /*when a message is received from the server*/Websocket.onmessage= function(msg) {Console.log ("service side says:" +msg.data); }; /*when closed*/Websocket.onclose= function() {Console.log ("Close Connection"); }; /*Send Message*/document.getElementById ("Send"). onclick= function () { varStr=document.getElementById ("content"). Value; Websocket.send (str); }</Script></HTML>
Node + H5 + WebSocket + Koa2 for simple multi-person chat