1

I'm currently doing this hack to handle the websocket's onmessage.

$scope.wsCon.onMessage = function(result) {
    $scope.wsCon.trigger(result.handler, result.data);
};

Problem here is that, onmessage is handling all the incoming requests through websocket.

But I need something like this:

$scope.wsCon.
    .send(data)
    .done(data, function (result) {
        // Deal with the result here
    })
    .fail(data, function() {
        // Show the error message
    })
    .complete(data, function() {
        // Do this always
    });

I know this is not achievable in websocket on single connection. But still, is there any way to produce effect something like the way jQuery does?

1 Answers1

1

WebSockets are not request/response based, so since there is no response required when you send a message, what do you expect to happen to finish that promise? the socket flushing the buffer? :) If the browser fails to send the message because the socket is dead, you will get an "onerror" message.

If you need confirmation of the message, or awaiting a response, you need to implement it yourself.

Please take a look at this answer : AngularJS and WebSockets beyond About this $connection service declared in this WebSocket based AngularJS application

Basically it is an example about creating a WebSocket service in AngularJS that can be used to request/response and publish/subscribe.

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()
});
Community
  • 1
  • 1
vtortola
  • 34,709
  • 29
  • 161
  • 263