是否有任何方法可以像处理jQuery中附加到XHR延迟对象的done方法处理程序一样处理websocket onmess

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

本文关键字:处理 方法 对象 程序 done onmess websocket 一样 延迟 任何 jQuery      更新时间:2024-01-17

我目前正在进行此破解,以处理websocket的onmessage。

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

这里的问题是,onmessage通过websocket处理所有传入的请求。

但我需要这样的东西:

$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
    });

我知道这在单连接的websocket中是无法实现的。但是,还有什么方法可以像jQuery那样产生效果吗?

WebSockets不是基于请求/响应的,因此,由于发送消息时不需要响应,您希望如何完成该承诺?插座正在冲洗缓冲区?:)如果浏览器因为套接字失效而无法发送消息,则会收到一条"oneror"消息。

如果您需要确认消息,或者等待响应,您需要自己实现它。

请看一下这个答案:AngularJS和WebSockets之外关于这个基于WebSocket的AngularJS应用程序中声明的$connection服务

基本上,这是一个关于在AngularJS中创建WebSocket服务的示例,该服务可用于请求/响应和发布/订阅。

基本上你可以监听信息:

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

听一次(非常适合请求/响应):

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

并发送消息:

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