无法在套接字连接中订阅主题。
app.factory('socket', [function() {
var stack = [];
var onmessageDefer;
var socket = {
ws: new WebSocket('wss://site.com:61015/'),
send: function(data) {
data = JSON.stringify(data);
if (socket.ws.readyState == 1) {
socket.ws.send(data);
} else {
stack.push(data);
}
},
onmessage: function(callback) {
if (socket.ws.readyState == 1) {
socket.ws.onmessage = callback;
} else {
onmessageDefer = callback;
}
}
};
socket.ws.onopen = function(event) {
for (i in stack) {
socket.ws.send(stack[i]);
}
stack = [];
if (onmessageDefer) {
socket.ws.onmessage = onmessageDefer;
onmessageDefer = null;
}
};
return socket;
}]);
如何在服务器的主题上实现pub/sub订阅以及如何在控制器中获得套接字消息?
请看下面的代码示例:AngularJS和WebSockets beyond
请注意,你必须自己实现订阅机制,因为WebSockets只是传输,没有底层的pub/sub。