简体   繁体   中英

Socket.io emit fires twice

I have set up a socket.io on my Node.js back end which emits certain events that AngularJS then captures and shows errors and changes some $rootScope variables. I have a problem where this emit seem to fire twice every time giving me two notifications and I don't know where the problem is

server.js (shortened)

var socket = require('socket.io');
var app = express();

var router = express.Router();
app.use('/api', router);

var server = app.listen(config.conn_port, function(){
    console.log("Server launched at port " + config.conn_port);
});

var io = socket.listen(server);

require('./api/routes')(router, connection, io);

routes.js

module.exports = function(router, connection, socket) {
    # Net event
    client.on('error', function () {
        socket.emit('serverDisconnected', {message: 'Connection ended', server_conn: false});
   });
}

app.js (AngularJS)

app.factory('socket', function ($rootScope) {
  var socket = io.connect();
  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);
          }
        });
      })
    }
  };
});

AngularJS Controller

dashboardModule.controller('dashboardMain', function ($scope, $http, $rootScope, Notification, socket) {
    socket.on('serverDisconnected', function (message) {
        Notification.error(message.message);
    });
});

Well, the answer was to move the AngularJS socket.on() to a service instead of a controller. The controller gets called twice which causes the duplicate firing.

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