简体   繁体   中英

Socket IO AngularJS(1.x) Factory Injection Multiple Emits

On my server side I'm using the following factory to refresh/emit data between my controllers:

angularApp.factory('socket', function ($rootScope) {
    var socket = io;

    return {
        on: function (eventName, callback) {
            socket.on(eventName, function () {
                var args = arguments;
                $rootScope.$apply(function () {
                    callback.apply(socket, args);
                });
            });
        },

        emit: function (eventName, data, callback) {
            socket.emit(eventName, data, function () {
                var args = arguments;
                $rootScope.$apply(function () {
                    if (callback) {
                        callback.apply(socket, args);
                    }
                });
            });
        }
    };
});

I emit signal from another controller to this(MainController) to start a data transfer to the connected clients

$scope.$on('beginDataTransfer', function() {
   socket.emit('dataTransfer', "SOME DATA");
}

The problem is if I don't check for "socket.connected == true" it will emit the data as many times as the clients reconnected. To my understanding the sockets don't get destroyed when the user disconnects for some reason.

I tried to check if the socket is connected back at the factory but it doesn't seem to work:

on: function (eventName, callback) {
    if(socket.connected){
    socket.on(eventName, function () {
        var args = arguments;
        $rootScope.$apply(function () {
            callback.apply(socket, args);
        });
    });
}

},

It emits multiple times as many times as the users reconnected.

Deleting the socket if it is disconnected causes issues out of $scope.$on(){} and even then it still emits multiple times.

delete socket;
socket = null;

Any suggestions ?

For some reason it turned out that the clients' connections didn't die out even when using "socket.disconnect()" or "socket.destroy()".

But using "ONCE" fixed the issue.

socket.**once**(eventName, function () {
   var args = arguments;
   rootScope.$apply(function () {
      callback.apply(socket, args);
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM