Node + H5 + WebSocket + Koa2 for simple multi-person chat

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.