This is another example of WebSocket integration with angularjs. I am taking angularjs front-end framework for websocket client application. Earlier I have shared Simple Websocket Example with Nodejs tutorial.

The WebSocket help to create realtime application, A real-time application allows information to be received as soon as it is published, rather than requiring a source to be checked periodically for updates.



We will consume websocket server into angular 1.4 example.We will use ngWebsocket module which is written in Angular-style syntax, very easy to import and use in your application.

How To Install ngWebsocket and Import

You can install ngWebsocket using bower or npn , but for angular 1.4, We need to download package from Github and added into head section of index.html file.

bower install ng-websocket

How To create WebSocket Server

We will create nodejs application that expose websocket server call.Created a new server.js file.

How Install ws libs in Nodejs

We will install ws libs into nodejs application using following command.

npm install ws

How To Create websocket nodejs server

We will create server.js file and add below code into this file.

// server.js const WebSocket = require('ws') const wss = new WebSocket.Server({ port: 8080 }) wss.on('connection', ws => { ws.on('message', message => { console.log(`Received message => ${message}`) }) ws.send('Hello! Message From Server!!') }) 1 2 3 4 5 6 7 8 9 10 11 12 // server.js const WebSocket = require ( 'ws' ) const wss = new WebSocket . Server ( { port : 8080 } ) wss . on ( 'connection' , ws = > { ws . on ( 'message' , message = > { console . log ( ` Received message = > $ { message } ` ) } ) ws . send ( 'Hello! Message From Server!!' ) } )

How To create WebSocket Client

We will create client application in angularjs. That listen server Websocket and received message from server.

I will create sample_example folder and created index.html file, That fill will have main controller and view.

Import ngWebsocket with Angular1.4

Open index.html file and include this file into head section of index.html file.

<script src="bower_components/ng-websocket/ng-websocket.js"></script> 1 <script src = "bower_components/ng-websocket/ng-websocket.js" > </script>

Import Module Into Angular App

I will create app.js file that will handle all operations of websocket angular application.First, import as a dependency module into this file.

'use strict'; angular.module('MyAwesomeApp', ['ngWebsocket']); 1 2 'use strict' ; angular . module ( 'MyAwesomeApp' , [ 'ngWebsocket' ] ) ;

How to Use WebSocket Module Into Angular App

This ngWebsocket module is provides an Angular Provider and a Service that help to call websocket server.