AngularJS发布/订阅者套接字connetcion

时间:2015-07-20 08:26:03

标签: angularjs sockets websocket

我无法在与服务器的套接字连接中订阅主题。



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




如何在服务器主题上实现发布/订阅以及如何在控制器中获取套接字消息?

1 个答案:

答案 0 :(得分:0)

请在以下位置找到代码示例:AngularJS and WebSockets beyond

请注意,您必须自己实现该订阅机制,因为WebSockets只是传输,没有底层的pub / sub。