node. JS Service Side
To install the WS module Support first
NPM Install WS
Service side (Server.js)
var GWS; var Websocketserver = require (' ws '). Server, new websocketserver ({port:9000 }), Wss.on (function (WS) { = ws; Console.log (' client connected '); Ws.on (function (message) { console.log (message); (Show, SetInterval);//Every 5 seconds the server pushes the message to the browser }) ; function Show () { gws.send (1122);}
shell> node Server.js
Browser client
<Script> if(window. WebSocket) {Console.log ("Support"); }Else{Console.log ("not supported"); } varws= NewWebSocket ('ws://localhost:9000'); Ws.onopen= function() {Console.log ("Open"); Ws.send ("Hello"); }; Ws.onmessage= function(evt) {Console.log (evt.data)}; Ws.onclose= function(evt) {Console.log ("websocketclosed!"); }; Ws.onerror= function(evt) {Console.log ("websocketerror!"); };</Script>
I wrote the WebSocket push example, every 5 seconds the server sends messages to the client browser (node. js and the browser)