0

I can't subscribe on a topic within socket connection with server.

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

How i can implement pub/sub subscriptions on a server's topic and how i can get socket messages in controller?

trigger
  • 489
  • 10
  • 26

1 Answers1

0

Please find a code example at: AngularJS and WebSockets beyond

Please note that you have to implement that subscription mechanism yourself since WebSockets are just are transport, there is no underlying pub/sub.

Community
  • 1
  • 1
vtortola
  • 34,709
  • 29
  • 161
  • 263
  • Thank you, i tried your example, but i can't implement subscription on a topic. Help please. When i should put the topics name for subscription on messages? – trigger Jul 20 '15 at 09:25
  • Because WebSockets do not implement any subscription system, they are just a communication channel. If you want to have topics and subscribe to them, you have to put a messaging framework in place. If you do not know how to do that, you may be interested in SignalR. – vtortola Jul 20 '15 at 10:05