Playing with websockets, angularjs and socket.io


I’m a big fan of websockets. I’ve got various post about them (here, here). Last months I’m working with angularjs projects and because of that I wanna play a little bit with websockets (with socket.io) and angularjs.

I want to build one angular service.

angular.module('io.service', []).
    factory('io', function ($http) {
        var socket,
            apiServer,
            ioEvent,
            watches = {};

        return {
            init: function (conf) {
                apiServer = conf.apiServer;
                ioEvent = conf.ioEvent;

                socket = io.connect(conf.ioServer);
                socket.on(ioEvent, function (data) {
                    return watches.hasOwnProperty(data.item) ? watches[data.item](data) : null;
                });
            },

            emit: function (arguments) {
                return $http.get(apiServer + '/request', {params: arguments});
            },

            watch: function (item, closure) {
                watches[item] = closure;
            },

            unWatch: function (item) {
                delete watches[item];
            }
        };
    });

And now we can build the application

angular.module('myApp', ['io.service']).

    run(function (io) {
        io.init({
            ioServer: 'http://localhost:3000',
            apiServer: 'http://localhost:8080/api',
            ioEvent: 'io.response'
        });
    }).

    controller('MainController', function ($scope, io) {
        $scope.$watch('question', function (newValue, oldValue) {
            if (newValue != oldValue) {
                io.emit({item: 'question', newValue: newValue, oldValue: oldValue});
            }
        });

        io.watch('answer', function (data) {
            $scope.answer = data.value;
            $scope.$apply();
        });
    });

And this’s the html

<!doctype html>
<html>

<head>
    <title>ws experiment</title>
</head>

<body ng-app="myApp">

<div ng-controller="MainController">

    <input type="text" ng-model="question">
    <hr>
    <h1>Hello {{answer}}!</h1>
</div>

<script src="assets/angular/angular.min.js"></script>
<script src="//localhost:3000/socket.io/socket.io.js"></script>

<script src="js/io.js"></script>
<script src="js/app.js"></script>

</body>
</html>

The idea of the application is to watch one model’s variable (‘question’ in this example) and each time it changes we will send the value to the websocket server and we’ll so something (we will convert the string to upper case in our example)

As you can read in one of my previous post I don’t like to send messages from the web browser to the websocket server directly (due do to authentication issues commented here). I prefer to use one server (a Silex server in this example)

include __DIR__ . '/../../vendor/autoload.php';

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;

$app = new Application(['debug' => true]);
$app->register(new G\Io\EmitterServiceProvider());

$app->get('/request', function (Application $app, Request $request) {

    $params = [
        'item'     => $request->get('item'),
        'newValue' => strtoupper($request->get('newValue')),
        'oldValue' => $request->get('oldValue'),
    ];

    try {
        $app['io.emit']($params);
        $params['status'] = true;
    } catch (\Exception $e) {
        $params['status'] = false;
    }

    return $app->json($params);
});

$app->run();

You can see the code within my github account.

About Gonzalo Ayuso

Web Architect. PHP, Python, Node, Angular, ionic, PostgreSQL, Linux, ... Always learning.

Posted on August 25, 2014, in AngularJS, js, node.js, php, silex, socket.io, Technology and tagged , , , , . Bookmark the permalink. 7 Comments.

  1. Hi Gonzalo,

    Thx for share your knowledge about these topics. Regarding to that post, I would like to make you a question about websockets. I’m trying to develop a prototype (first of all, to learn) based on the powerful of HTML5, JavaScript (running over Node.js) and websockets.

    My main doubt is about the performance, because what the prototype aims is to send a bunch of data like a streaming server (but in this case, I’ll send JSONs instead audio/video). Once the client is connected to the server, the server side will send that blocks of information in periods of 1 second. My question is: Will be my server ready to support and serve that behaviour with 100 clients connected at same time? And 1000? Do you know a estimation to calculate this rate?

    I’m Android developer in my spare time, and I would like to evolve my prototype adding a new kind of client: an android client. For this scenario, I’d also want to receive those blocks of information in the mobile device in order to perform a minimal processing and show it.

    Is all of this reasoning a crazy idea?
    Thanks again for your time and for your reply.

  2. Hello Gonzalo, thanks a lot for sharing that. It’s very useful.

  3. Nice example,

    I was trying to communicate a web app with an app developed in C++ (that is the app that starts the listener). Everything seem to work but every time that I fire the .emit function,the socket was closed. Any clue about the problem??

    • Gonzalo Ayuso

      It’s difficult to answer to this kind of questions. Anyway if the socket is closed normally is because someone closes it (or due to crash, of course). It there isn’t a crash you can check who closes the connection. You only have two alternatives: client or server. Anyway your must realize that this isn’t a simple tcp server. It’s a tcp server, indeed, but it’s also a websocket server (with its own protocol). I don’t have experience with c++ and websocket servers (client it’s the same)

  4. Hello Gonzalo I am developing an application in ionic 2, the idea is while recording the video save data on a web server, my question is if it is possible to save the video through socket.io with cordoba and angular, thanks

    • Yes. Its possible, but websockets aren’t our best friends to handle video streams. To do this the WebRTC is the best solution

  1. Pingback: Yet Another example of WebSockets, socket.ioa and AngularJs working with a Silex backend | Gonzalo Ayuso | Web Architect

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: