AngularJS and WebSockets beyond

后端 未结 2 2126
执笔经年
执笔经年 2020-12-01 05:20

I just read this post, and I do understand what the difference is. But still in my head I have the question. Can/Should I use it in the same App/Website? Say I want the Angu

2条回答
  •  忘掉有多难
    2020-12-01 06:06

    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.

提交回复
热议问题