Skip to main content
nodejs-websocket-example

WebSocket Integration With Angularjs

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

The WebSocket help to create a real-time 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 the WebSocket server into the angular 1.4 client application. 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!!')
})

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>

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']);

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.

angular.controller('MyCtrl', function ($websocket) {
  var ws = $websocket.$new('ws://localhost:3001');

  ws.$on('$open', function () {
    ws.$emit('sendEvent', 'test message from server'); // it sends the event 'sendEvent' with data 'test'
  })
  .$on('sendEvent', function (message) { // it listents for 'incoming event'
    console.log('something incoming from the server: ' + message);
  });
});

Leave a Reply

Your email address will not be published. Required fields are marked *