Simple socket.io Using Node js and angular js

Simple socket.io Using Node js and angular js

To see the working demo open following link in two different client (Browser).

Demo Link

Setting up the Project

First we need to create a project, do this with the following command

npm init

Installing Back-End Dependencies

Create a server folder inside the root directory of the app and inside the folder, create a package.json file, adding the following:

{
  "name": "simplSocketChatApp",
  "version": "1.0.0",
  "description": "",
  "scripts": {
  "start": "node server.js",
   "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Avdhesh(ej)",
  "license": "ISC",
  "dependencies": {
    "ejs": "^2.5.7",
    "express": "^4.16.2",
    "socket.io": "^2.0.4"
  }
}

Save the file and execute npm install. This installs the all dependencies.

Socket.io Server

Create a server.js file and add the following code:

var express = require('express');
var path = require('path');
var app = express();
var server = require('http').createServer(app);
app.use('/', express.static(path.join(__dirname, '/UI')));
var io = require('socket.io')(server);
io.on('connection', function(client) {
    client.on('disconnect', function() {
    console.log("disconnected")
    });
    client.on('room', function(data) {
        client.join(data.roomId);
        console.log(' Client joined the room and client id is '+ client.id);

    });
    client.on('toBackEnd', function(data) {
               client.in(data.roomId).emit('message', data);
    })
});
server.listen(3000);

Installing Front-End Dependencies

Create a bower.json file in the UI directory of the project and add the following code:


 {
  "name": "simplchat",
  "description": "A simple socket app",
  "authors": [
    "Avdhesh"
  ],
  "license": "ISC",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "test",
    "tests"
  ],
  "dependencies": {
    "socket.io-client": "sio-client#^1.4.8",
    "angular-socket-io": "^0.7.0",
    "angular-local-storage": "^0.7.1"
  }
}
  • angular-local-storage: Used for storing data in local storage. In the following project it’s used to store the name of the user, and the current room.
  • sio-client: The socket.io JavaScript client.
  • angular-socket-io: Allows us to use socket.io within Angular.

We are using angular material for DOM.

index.html

Directory: project_folder/UI/

Start by opening the index.html file inside the UI directory and linking the script files.

<html lang="en">

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css">
</head>

<body ng-app="simpleSocketApp" ng-cloak>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script>    <script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.js"></script>
    <script src="lib/angular-local-storage/dist/angular-local-storage.min.js"></script>
    <script src="lib/socket.io-client/socket.io.js"></script>
    <script src="http://localhost:3000/socket.io/socket.io.js"></script>
    <script src="lib/angular-socket-io/socket.min.js"></script>
    <script src="js/app.js"></script>
    <div ng-include="'view/home.html'"></div>
</body>
</html>

Home.html

Now we are going to create simple view for the sending messages.

<div ng-controller="homeController">
    <md-input-container>
        <label>Add message</label>
        <input ng-model="message.input">
    </md-input-container>
    <md-button ng-click="add()" class="md-warn">Send</md-button>

    <md-toolbar layout="row" class="md-hue-3">
        <div class="md-toolbar-tools">
            <span>Normal</span>
        </div>
    </md-toolbar>

    <md-content>
        <md-list flex>
            <md-subheader class="md-no-sticky">Updated List</md-subheader>
            <md-list-item class="md-3-line" ng-repeat="item in array" ng-click="null">

                <div class="md-list-item-text" layout="column">
                    <h3>{{ item.data.input }}</h3>
                    <h3>{{ item.date | date:'medium'}}</h3>

                </div>
            </md-list-item>
            <md-divider></md-divider>
        </md-list>
    </md-content>
</div>

Adding the Dependencies

Open the /js/app.js file and include the following services

  • LocalStorageModule: Allows us to use local storage.
  • btford.socket-io: Allows us to use socket.io.

Add following lines in the app.js

var app = angular.module('MySocektApp', ['ngMaterial', 'LocalStorageModule', 'btford.socket-io']);

app.service('SocketService', ['socketFactory', function SocketService(socketFactory) {
    return socketFactory({
        ioSocket: io.connect('http://localhost:3000')
    });
}]);

app.controller('homeController', function($scope, localStorageService, SocketService) {

    $scope.array = [];
    $scope.message = {};
    SocketService.emit('room', { roomId: "temp" });

    $scope.add = function() {
        SocketService.emit('toBackEnd', {roomId:'temp', data: $scope.message, date: new Date() })
        $scope.array.push({ data: $scope.message, date: new Date() })
    }

    SocketService.on('message', function(msg) {
        $scope.array.push(msg)
    });

})

Conclusion

In above tutorial we have learned how to create a socket application with Angular js and node js . This application is basic idea of socket.io featured nodejs but we can use this idea ine following area:

  • Angular powered cross chat app
  • A real time video calling module using