当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Is there any way to handle websocket onmessage handler just like done method handlers attached to XHR deferred objects in jQuery

问题描述:

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?

网友答案:

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()
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: