1

Answers in Duplicate are not referring to angularjs library that is being used in my code because the way angular setup angular-socket-io is not similar to the answers provided in duplicate!

Just started working on socket.io first time i have found angular-socket-io library to work on client side but it looks little complicated,i just want to send message from server to client using angular-socket library but its not happening any idea what is implemented wrong in below code ?

index.html

<script src="bower_components/socket.io-client/socket.io.js"></script>
<script src="bower_components/angular-socket-io/socket.js"></script>

server.js

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

    io.on('connection', function(client) {
        console.log('Client connected...');
       io.emit('message', message);
    });


server.listen(3000);

angularSOcketFactory.js

angular.module('loggingApp').factory('mySocket', function (socketFactory) {
    'use strict';
    return socketFactory();
});

angularCtrl.js

 $scope.$on('socket:someEvent', function (ev, data) {
      $scope.theData = data;
    });
3
  • Are you getting any specific errors? And what does your server code look like? Commented Jul 8, 2016 at 15:22
  • Possible duplicate of AngularJS does not refresh view with socket.io Commented Jul 8, 2016 at 15:26
  • getting error : Failed to load resource: the server responded with a status of 404 (Not Found) Commented Jul 8, 2016 at 15:32

1 Answer 1

1

There's an excellent tutorial on how to create your own socket.io provider for angular.

I've used it successfully in my AngularJS apps, I also have a completed version of the source in that gist. It is setup for Browserify but you can undo that by just getting rid of the the two require(''); statements up top in the file.

Here's the source for the Socket.io provider, you'll just need to hook this into your Controllers. All credit belongs to Maciej Sopylo for putting the tutorial out there with this approach.

(function () {
  'use strict';

  var angular = require('angular');
  var io = require('socket.io-client');

  angular
    .module('socket.io', [])
    .provider('$socket', $socketProvider);

  /* @ngInject */
  function $socketProvider() {
    var ioUrl = '';
    var ioConfig = {};

    // Private Function to assign properties to ioConfig
    function setOption(name, value, type) {
      if (typeof value !== type)
        throw new TypeError('\'' + name + '\' must be of type \'' + type + '\'');
      else
        ioConfig[name] = value;
    }

    this.$get = function $socketFactory($rootScope) {
      var socket = io(ioUrl, ioConfig);

      return {
        on: function on(event, callback) {
          socket.on(event, function() {
            var resData = arguments;

            $rootScope.$apply(function() {
              callback.apply(socket, resData);
            });
          });
        },
        off: function off(event, callback) {
          if (typeof callback === 'function')
            socket.removeListener(event, callback);
          else
            socket.removeAllListeners(event);
        },
        emit: function emit(event, data, callback) {
          if (typeof callback === 'function') {
            socket.emit(event, data, function() {
              callback.apply(socket, arguments);
            });
          }
          else
            socket.emit(event, data);
        }
      };
    };

    this.setConnectionUrl = function setConnectionUrl(url) {
      if (typeof url === 'string')
        ioUrl = url;
      else
        throw new TypeError('url must be of type string');
    };

    this.setPath = function setPath(value) {
      setOption('path', value, 'string');
    };

    this.setConnectTimeout = function setConnectTimeout(value) {
      setOption('connect timeout', value, 'number');
    };

    this.setTryMultipleTransports = function setTryMultipleTransports(value) {
      setOption('try multiple transports', value, 'boolean');
    };

    this.setReconnect = function setReconnect(value) {
      setOption('reconnect', value, 'boolean');
    };

    this.setReconnectionDelay = function setReconnectionDelay(value) {
      setOptions('reconnection delay', value, 'number');
    };

    this.setReconnectionLimit = function setReconnectionLimit(value) {
      setOptions('max reconnection attempts', value, 'number');
    };

    this.setSyncDisconnectOnUnload = function setSyncDisconnectOnUnload(value) {
      setOptions('sync disconnect on unload', value, 'boolean');
    };

    this.setAutoConnect = function setAutoConnect(value) {
      setOptions('auto connect', value, 'boolean');
    };

    this.setFlashPolicyPort = function setFlashPolicyPort(value) {
      setOptions('flash policy port', value, 'number');
    };

    this.setForceNewConnection = function setForceNewConnection(value) {
      setOptions('force new connection', value, 'boolean');
    };
  }

})();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.