AngularJS and WebSockets beyond

Javascript supports WebSocket, so you don’t need an additional client side framework to use it. Please take a look at this $connection service declared in this WebSocket based AngularJS application.

Basically you can listen for messages:

   $connection.listen(function (msg) { return msg.type == "CreatedTerminalEvent"; }, 
        function (msg) {
            addTerminal(msg);
            $scope.$$phase || $scope.$apply();
   });

Listen once (great for request/response):

    $connection.listenOnce(function (data) {
        return data.correlationId && data.correlationId == crrId;
    }).then(function (data) {
        $rootScope.addAlert({ msg: "Console " + data.terminalType + " created", type: "success" });
    });

And send messages:

    $connection.send({
        type: "TerminalInputRequest",
        input: cmd,
        terminalId: $scope.terminalId,
        correlationId: $connection.nextCorrelationId()
    });

Usually, since a WebSocket connection is bidirectional and has a good support, you can also use it for getting data from the server in request/response model. You can have the two models:

  • Publisher/Subscriber: Where the client declares its interest in some topics and set handlers for messages with that topic, and then the server publish (or push) messages whenever it sees fit.

  • Request/response: Where the client sends a message with a requestID (or correlationId), and listen for a single response for that requestId.

Still, you can have both if you want, and use REST for getting data, and WebSocket for getting updates.

In server side, you may need to use Socket.io or whatever server side framework in order to have a backend with WebSocket support.

Leave a Comment