AJ_83
AJ_83

Reputation: 299

Creating a TCP Socket in AngularJS

In PHP it is easy to create, connect an interact with a TCP socket (http://www.codeproject.com/Tips/418814/Socket-Programming-in-PHP, the Client part).

How can I accomplish this in AngularJS? Tried the module on following site: https://github.com/BHSPitMonkey/angular-net-sockets, but failed. An example on this site would have been helpful to me.

EDIT

How can I use that in my controller? I'm getting the error: 'factory must return a value'.

This is what I am trying to accomplish:

app.controller('controller', ['$scope', 'netsockets',  function ($scope, netsockets) {
$scope.username = "test";

$scope.send_socket = function(){
    socket.connect('1.1.1.1','1111');
    socket.sendData('hello world');
    socket.disconnect();
    socket.close();
};

}]);

This is my factory:

factory('netsockets', function(NetSocket) {
    return {
    init: function(){
        var socket = new NetSocket({
          onConnect: function(){
              alert('I\'m connected!');
          },
          onDisconnect: function(){
              alert('I\'m disconnected!');
          }
        });
    }
}
});

Upvotes: 1

Views: 6076

Answers (1)

alberto-bottarini
alberto-bottarini

Reputation: 1231

angular.module('myApp.services', []).
  factory('MyService', function(NetSocket) {
    var socket = new NetSocket({
      onConnect: function() {
        alert('I\'m connected!');
      },
      onDisconnect: function() {
        alert('I\'m disconnected!');
      }
    });
    socket.connect('1.1.1.1','1111');
    socket.sendData('hello world');
    socket.disconnect();
    socket.close();
});

EDIT

your factory does not return anything. Try with this:

factory('netsockets', function(NetSocket) {
    return new NetSocket({
          onConnect: function(){
              alert('I\'m connected!');
          },
          onDisconnect: function(){
              alert('I\'m disconnected!');
          }
        });

});

Upvotes: 1

Related Questions