我目前正在做这个 hack 来处理 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 那样的效果吗?
最佳答案
WebSocket 不是基于请求/响应的,因此,由于发送消息时不需要响应,您预计会发生什么来完成该 promise ?套接字刷新缓冲区? :) 如果浏览器由于套接字已死而无法发送消息,您将收到“onerror”消息。
如果需要确认消息,或者等待回复,则需要自己实现。
请看一下这个答案:AngularJS and WebSockets beyond关于此$connection service在此声明WebSocket based AngularJS application
基本上,这是一个关于在 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()
});
关于javascript - 有没有办法处理 websocket onmessage 处理程序,就像附加到 jQuery 中的 XHR 延迟对象的完成方法处理程序一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28577139/