GithubHelp home page GithubHelp logo

blocshop / sockets-for-cordova Goto Github PK

View Code? Open in Web Editor NEW
135.0 135.0 125.0 851 KB

Cordova plugin for socket network communication

JavaScript 2.46% Java 7.32% Objective-C 71.33% C 1.10% Shell 9.38% AppleScript 0.39% CSS 1.19% C# 6.22% HTML 0.61%

sockets-for-cordova's People

Contributors

mobratil avatar toadi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sockets-for-cordova's Issues

new Socket() fails

As per the given instruction, I have installed the plugin and then written a function in app.js that contains -
var v = new Socket();

When I run my app using 'ionic serve', I get the following error in Chrome browser -
ReferenceError: Socket is not defined

Could anybody find my mistake? Any help would be highly appreciated...

Socket send doenst work

Hi and THANKS for this plugin, this is awesome and incredible!!!!
But the send command seems not to work, i can connect to the server, receive commands from the server, but cant send.
I used it in two ways:
1°)
var cmdToSendToServer = $("#cmdToSendToHost").val();

        var data = new Uint8Array(cmdToSendToServer.length);
        for (var i = 0; i < data.length; i++) {
          data[i] = cmdToSendToServer.charCodeAt(i);
        }
        socket.send(data);

2°)
var cmdToSendToServer= "TESTE";

        var data = new Uint8Array(cmdToSendToServer.length);
        for (var i = 0; i < data.length; i++) {
          data[i] = cmdToSendToServer.charCodeAt(i);
        }
        socket.send(
                data,
                function(){
                    receiver.html('Data successful sended!');
                },
                function(message){
                    receiver.html('Data send error: '+message);
                }
        );

Am i wrinting wrong code?

Thanks!

Lost byte when receive?

I've write an app that exchange data with a device by telnet using this plugin. I send a command and waiting for the reply. All seems to work, but the reply from the device is often too short, as the plugin lost the tail of the device transmission. The socket.onData is atomic? Return the entire tcp packet? Or is called more time until the packet is finished?

Dont work in Sansung S7, S8

hi

I have an application that works perfectly with this pluggin, however for the last generation phones (sansung s7, s8...) it is not connected via telnet.

Can you help me?

Connection Refused in Ionic on Android

When using sockets-for-cordova in an ionic application, I get the error at the end of this message when calling Socket.open().

I am using the exact same code in a non-ionic cordova app, and it works fine.

I have verified that <uses-permission android:name="android.permission.INTERNET" /> is making it into my AndroidManifest.xml, and I have added the following to my config.xml in case it is a cordova whitelist issue.

<access origin="*"/>
<allow-navigation href="*"/>
<allow-intent href="*"/>

I also see the following message regarding whitelist, but I have not been able to resolve it, and I don't know if it is relevant or not.

D/SystemWebChromeClient(20861): file:///android_asset/www/plugins/cordova-plugin-whitelist/whitelist.js: Line 25 : No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin.
I/chromium(20861): [INFO:CONSOLE(25)] "No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin.", source: file:///android_asset/www/plugins/cordova-plugin-whitelist/whitelist.js (25)

Here is the error I get when trying Socket.open():

D/SystemWebChromeClient(28872): file:///android_asset/www/js/connect.js: Line 11 : Connect.connect() 192.168.2.193
I/chromium(28872): [INFO:CONSOLE(11)] "Connect.connect() 192.168.2.193", source: file:///android_asset/www/js/connect.js (11)
E/SocketAdapterImpl(28872): Error during connecting of socket
E/SocketAdapterImpl(28872): android.system.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
E/SocketAdapterImpl(28872): at libcore.io.Posix.connect(Native Method)
E/SocketAdapterImpl(28872): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)
E/SocketAdapterImpl(28872): at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
E/SocketAdapterImpl(28872): at libcore.io.IoBridge.connect(IoBridge.java:122)
E/SocketAdapterImpl(28872): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
E/SocketAdapterImpl(28872): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
E/SocketAdapterImpl(28872): at java.net.Socket.connect(Socket.java:882)
E/SocketAdapterImpl(28872): at java.net.Socket.connect(Socket.java:825)
E/SocketAdapterImpl(28872): at cz.blocshop.socketsforcordova.SocketAdapterImpl$1.run(SocketAdapterImpl.java:38)
E/SocketAdapterImpl(28872): at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
E/SocketAdapterImpl(28872): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
E/SocketAdapterImpl(28872): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
E/SocketAdapterImpl(28872): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
E/SocketAdapterImpl(28872): at java.lang.Thread.run(Thread.java:818)
D/SystemWebChromeClient(28872): file:///android_asset/www/js/control.js: Line 10 : Control
I/chromium(28872): [INFO:CONSOLE(10)] "Control", source: file:///android_asset/www/js/control.js (10)
W/BindingManager(28872): Cannot call determinedVisibility() - never saw a connection for the pid: 28872

Find socket port number

Hi i am wanting to know if there is any way to find the port number of the socket once a successful socket connection has been made? Something like getSocketInfo()??? or is there a way to find the connections port in vanilla javascript?

Any help is much appreciated
Thanks

Connection Refused

I'm getting connection refused everytime I try and communicate with a server that is setup on a another device. Should I be able to set this up on 2 devices and communicate via the socket, or does it need an actual server?

receive method - Cordova sample for receving tcp message

Hi,

I'm facing an issue related to socket's Receive function when we call it in an app that was built using PhoneGapBuild.

Within the library there is the receive method?
there is a way to implement it?
I have to receive data from a socket connected to a specific address.

Looking forward to answers and support. Thanks.

Multiple requests in parallel on IOS get mixed up

Hello,

First off, thanks for creating this plugin!

I believe there is an issue with the iOS code when multiple requests are kicked off concurrently.

The data events that I receive after opening multiple connections appear to be randomly swapping between the different connections. In other words, if I open up two connections (A and B), I'll get data from connection A in connection B's data event, and A's data will go to connection B's data event.

I have not tested on windows phone, but I have beat on the android code and I've not been able to recreate it there. It only appears to affect the iOS code.

I may try to dig into it, but I'm not really fluent in objective C.

Thanks,
Kyle

/cc @mohlsen @yaworsw @kwpeters

Connectivity drop causes application to crash

If I include this plugin in an application and have the socket open, closing for example the wifi connection from the iphone / ipod settings will result in a crash of the application due to the close method from inside the plugin in the iOS implementation (plugin throws IllegalArgumentException).

upd?

Will be possible to also have udp sockets support?

How ot use this plugin?

Hi, I'm new to cordova and trying to use it with Ionic Framework. I have an existing project that works and has multiple pages.

I've added this plugin using: "cordova plugin add cz.blocshop.socketsforcordova" and I confirmed that it was added successfully under plugins folder.

After that I added the following code in my controller, which is called with a press of a "Connect" button on the page: "var socket = new Socket();"

When I run the code in Chrome browser with Netbeans connector, I get the following error:

Error: Can't find variable: Socket
connect@http://localhost:8383/nj_obd/js/controller/inspectionController.js:45:23
http://localhost:8383/nj_obd/lib/ionic/js/ionic.bundle.js:19687:25
http://localhost:8383/nj_obd/lib/ionic/js/ionic.bundle.js:42909:20
$eval@http://localhost:8383/nj_obd/lib/ionic/js/ionic.bundle.js:21549:27
$apply@http://localhost:8383/nj_obd/lib/ionic/js/ionic.bundle.js:21647:27
http://localhost:8383/nj_obd/lib/ionic/js/ionic.bundle.js:42908:18
http://localhost:8383/nj_obd/lib/ionic/js/ionic.bundle.js:11841:13
forEach@[native code]
forEach@http://localhost:8383/nj_obd/lib/ionic/js/ionic.bundle.js:9351:17
eventHandler@http://localhost:8383/nj_obd/lib/ionic/js/ionic.bundle.js:11840:11
dispatchEvent@[native code]
triggerMouseEvent@http://localhost:8383/nj_obd/lib/ionic/js/ionic.bundle.js:2740:19
tapClick@http://localhost:8383/nj_obd/lib/ionic/js/ionic.bundle.js:2729:19
tapMouseUp@http://localhost:8383/nj_obd/lib/ionic/js/ionic.bundle.js:2799:12 (12:04:48:580 | error)

Any idea what that means? Thanks!

Poor performance

Hi,
I try to use your plugin to download ~6MB of data, but unfortunately it:
a. uses 100% CPU and makes the application unresponsive
b. the transfer is quite slow
Here are some benchmarks, I tried to download the same data on different devices, the application contained only the download code:
2s - ~3M/s - Mac (same Wi-Fi)
14,6s - ~420KB/s - emulator
72s - ~80KB/s - iPad
+5 min - Samsung Galaxy S3 mini - ~20KB/s...

Is there a chance for any improvements?

Socket Stuck CLOSING

Running this on iOS my socket frequently gets stuck in the CLOSING state. Is there any way to destructively close a socket.

Unsuccessful opening of Socket

Hi,

Socket.open method's error callback function returns with a following message:
"-[__NSCFString stringValue]: unrecognized selector sent to instance 0x7b7ca5f8d00"

On debugging the issue at our ends, we found that the first line of SocketAdapter.open() method throws exception (mentioned above).
Here is that line:
NSLog(@"Setting up connection to %@ : %@", host, [port stringValue]);

Note:
host=10.10.100.254
port=4000

The issue surfaced on iOS environment (iPhone 6).
If we comment the logging code, everything works fine and open method returns successfully.

We will be looking forward to your support on this matter. Thanks.

Socket is not defined

I am having real trouble getting this plugin to work. I am using windows and phonegap 5.1.1. Should I be able to run the index.html locally when it is built in the platforms/ios folder?

I am getting Socket is not defined when I put in the line of code

"var socket = new Socket();"

cordova.js and js/index.js are referenced above it and I can see the reference to the socket.js file in the console..

Thanks in advance.

Socket automatically closed after seconds

Hello,

thanks for this plugin. I manage to open the socket and write messages.
But after waiting some seconds the connection automatically close and I've this message :
"Connection reset by peer"

Is this a bug or normal process ? Do you know how to persist the connection ?

Thanks in advance

Connection Refused on Android

    document.addEventListener("deviceready", function () {
        var socket = new Socket();
        socket.onData = receiveData;
        socket.onError = function (errorMessage) {
            alert("Error occured, error: " + errorMessage);
        };
        socket.onClose = function (hasError) {
            console.info("Socket closed, hasErrors=" + hasError);
            setDisconnected();
        };
        socket.open(
            "130a8d8b.all123.net",
            10086,
            setConnected,
            function (errorMessage) {
                alert("Error during connection, error: " + errorMessage);
            });

        function setConnected() {
            var menuEl = document.getElementById("menu");
            menuEl.style.display = "none";
            var consoleEl = document.getElementById("console");
            consoleEl.style.display = "block";
        }

        function receiveData(data) {
            var chars = new Array(data.length);
            for (var i = 0; i < data.length; i++) {
                chars.push(String.fromCharCode(data[i]));
            }
            var dataString = chars.join("");
            dataString.split(/(?:\r\n|\r|\n)/g).forEach(addTextToOutputElement);
        }
    })

config.xml

  <?xml version='1.0' encoding='utf-8'?>
<widget id="com.example.hello" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>HelloWorld</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="[email protected]" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <plugin name="cordova-plugin-whitelist" spec="1" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
    <plugin name="cz.blocshop.socketsforcordova" spec="^1.1.0" />
    <engine name="android" spec="7.1.4" />
</widget>

I got
failed to connect to 130a8d8b.all123.net/127.10.141.140 (port 10086): connect failed: ECONNREFUSED (Connection refused)

Update license to New BSD License

Hi,

I'm thinking of using this library, however the current 4 clause BSD license is an issue for me due to clause number 3:

All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the Blocshop s.r.o..

This clause number 3 of BSD old license makes it not suitable to use for advertising.
Would it be possible to change the license for the New BSD License (where clause number 3 is removed) ?

Thanks

How we get response

Hi,

my socket like below
`//scoket send data to machine
$scope.taskName = $rootScope.task_name;
$scope.flightName = $rootScope.flight_name;

                var socket=new Socket();
                socket.open("192.168.4.1",80,function(){
                    console.log("success");

                   var dataString = ""+$scope.flightName+",test,"+$scope.taskName+","+$scope.start_time+",start";
                   var data = new Uint8Array(dataString.length);
                   for (var i = 0; i < data.length; i++) {
                     data[i] = dataString.charCodeAt(i);
                   }
                   socket.write(data,function(res){alert("Data send Successfully")},function(err){console.log(err);alert(err)});
                },function(error){alert(error)});
                socket.shutdownWrite();
                socket.close();`
  1. First it successfully connect the socket.
  2. Now i am able to send write the msg.
  3. How can i get response ?
    socket.write(data,function(res){alert("Data send Successfully")},function(err){console.log(err);alert(err)});
    in this line i print res. But it is showing only ok.

example needed

Hi.

thanks for the plugin, can you also write how to use this plugin?

Write Method Stop Working

Hi,

I'm facing an issue related to socket's Write function when we call it in an app that was built using PhoneGapBuild.

Here is the code:

BaseController.prototype.OnConnect = function (k) {
 that.timerHandle = window.setInterval(function () {
            that.SendReadCommand.call(that);
},100);
}
BaseController.prototype.SendReadCommand = function () {
    try {        
        this.socket.write(this.dpGenerator.SetReadCommandDataPack(), this.WriteOnSuccess, this.WriteOnError);
        this._sendCommandCounter++;
    }
    catch (ex) {
        RaiseAPIExceptionEvent(ex);
    }
}

The Write function successfully executes and WriteOnSuccess callback function is called. However, it stops working after ~1000+ calls. Once it stop working, neither success nor failed callback functions is called, in other words Write function seems halted.
Interestingly, this behavior is only observed when application is built on PhoneGapBuild environment, however, if application is built using Cordova CLI and plugins are locally added to project then Write function never stop working even after 1000+ calls.
In another observation, once the function stops working if we double tap home button and go to multi-tasking view, Write function switches from halted state to normal state and success callback methods start calling, against pending Write calls. Right after executing pending Write calls it halts again.

Just to share few things related to platform and devices, the issue is only observed and checked on iOS platform so far, and the TCP device is connected through WiFi which means there is not Internet access while communicating with TCP device using socket API/plugin.

Note: cz.blocshop.socketsforcordova v1.1.0 is being used.

Looking forward to answers and support. Thanks.

undefined is not a function

_.extend Meteor,

    socket: (content) ->

        socket = new Socket()
        console.log socket

        # socket.open '192.168.4.1', 8888, ->
        socket.open '192.168.1.191', 8888, ->

            data = new Uint8Array(content.length)
            i = 0
            while i < data.length
                data[i] = (content).charCodeAt(i)
                i++
            socket.shutdownWrite(data)

I20150804-14:23:38.908(8) (android:http://meteor.local/client/lib/extend.coffee.js:6) [object Object]
I20150804-14:23:38.932(8) (android:http://meteor.local/cordova.js:1059) processMessage failed: Error: TypeError: undefined is not a function
I20150804-14:23:38.948(8) (android:http://meteor.local/cordova.js:1060) processMessage failed: Stack: TypeError: undefined is not a function
I20150804-14:23:38.948(8)? at Object.cordova.callbackFromNative (http://meteor.local/cordova.js:293:54)
I20150804-14:23:38.948(8)? at processMessage (http://meteor.local/cordova.js:1054:21)
I20150804-14:23:38.948(8)? at Function.androidExec.processMessages (http://meteor.local/cordova.js:1091:13)
I20150804-14:23:38.948(8)? at pollOnce (http://meteor.local/cordova.js:956:17)
I20150804-14:23:38.948(8)? at pollOnceFromOnlineEvent (http://meteor.local/cordova.js:946:5)
I20150804-14:23:38.949(8) (android:http://meteor.local/cordova.js:1061) processMessage failed: Message: S01 SocketsForCordova1060265372 sOK
I20150804-14:23:38.949(8) (android:http://meteor.local/plugins/cz.blocshop.socketsforcordova/socket.js:61) Uncaught TypeError: object is not a function

Plugin doesn't respond or do anything

Hi!

I'm trying to fetch any sort of respond from the plugin (error from not finding the server or if it is found) but I can't get it working... The plugin has been added successfully with the cordova plugin add -command and the code is here: http://pastebin.com/ULCgrA41

Could you help me?

Btw don't bother on these weird words in the append commands, these are Finnish swear words :D

socket.open fails with error ENETUNREACH (Network is unreachable)

I'm trying to connect to a Wifi OnBoard Diagnostic(OBD) connector interface for a car's OBD port from my ionic application. But the connection fails with the error message given below my code.

I even changed from $ionicPlatform.ready() to angular.bootstrap method of initializing my app like some other posts had suggested. But still the same issue. Any ideas?

function str2ab(str) {
    // var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
    var bufView = new Uint8Array(str.length);
    for (var i=0; i<bufView.length; i++) {
      bufView[i] = str.charCodeAt(i);
    }
    return bufView;
  }

  function connectToHost(host, port) {
    var socket = new Socket();
    socket.onError = function(errorMessage) {
      console.log("Error occured, error: " + errorMessage);
    };
    socket.onClose = function(hasError) {
      console.info("Socket closed, hasErrors=" + hasError);
    };
    socket.onData = function (data){
      var chars = new Array(data.length);
      for (var i = 0; i < data.length; i++) {
          chars.push(String.fromCharCode(data[i]));
      }
      var dataString = chars.join("");
      console.log(dataString);
    };
    socket.open(
      host,
      port,
      function(success) {
        console.log(success);
      },
      function(errorMessage) {
        console.log("Error during connection, error: " + errorMessage);
      }
    );
  }

  $scope.OBDPlugNames = [];
  function connectToPlug(){
    var config = $cordovaWifiWizard.formatWPAConfig($localstorage.get('wifiName'), $localstorage.get('wifiPassword'));
    $cordovaWifiWizard.isWifiEnabled().then(function (bool){
      if(bool){//It's enabled
        $cordovaWifiWizard.getCurrentSSID().then(function (res){
          if(res !== config.SSID){//connected to a wifi network besides the OBDII plug?
            $cordovaWifiWizard.disconnect(res).then(function (){//disconnect from current network
              $cordovaWifiWizard.connectNetwork(config.SSID)//connect to OBDII plug
              .then(function (res){
                $scope.OBDConnected = true;
                var PID = str2ab("010F0D");
                var disableEcho = str2ab("ATE0");
                connectToHost('MY_IP', MY_PORT)
              });
            });
          } else {
            $cordovaWifiWizard.connectNetwork(config.SSID)//connect to OBDII plug
            .then(function (res){
              $scope.OBDConnected = true;
              var PID = str2ab("010F0D");
              var disableEcho = str2ab("ATE0");
              connectToHost('MY_IP', MY_PORT)
            });
          }
        });
      } else {//it's disabled
        $ionicPopup.alert({
          template:  "<h3>Wifi is disabled</h3><br><strong><p>Please enable wifi and try again</p></strong>"
        });
      }
    });
  }

returns the following error;

Error during connection, error: failed to connect to /MY_IP (port MY_PORT): connect failed: ENETUNREACH (Network is unreachable)

SSH connections

Is it possible to open an ssh connection using this plugin?

Connect timeout ?

Hello,

Thank you for this plugin. How I can use connect timeout parameter?

thank you.

How to properly integrate in Ionic 3

Hi,
I've installed the plugin with npm i blocshop-sockets-for-cordova-plugin and added it under cordova.js in index.html as instructed.

If I use this.socket = new Socket(); in my constructor, the build fails with
Cannot find name 'Socket'.
Error: Failed to transpile program

If I use this.socket = new (<any>window).Socket();

When building the app with
ionic cordova emulate ios --target "iPhone-XS-Max, 12.4"
or
ionic cordova emulate android

the builds succeed but do not contain the file socket.js and Chrome console says
window.Socket is not a constructor.

I'm using
ionic-angular 3.9.2
Cordova android:7.0.0, ios: 5.1.1

Error function is not invoked if the socket could not be opened - iOS

On IOS, if I try to open a socket to a non-existent IP the specified error function is not invoked.

This is the code:

var socket = new Socket();
socket.onError = function(errorMessage) { console.log( errorMessage ); };
socket.onClose = function(hasError) { console.log( hasError ); };
socket.open( "192.168.1.2", 502, function(){ console.log("Connected"); }, function(errorMessage){ console.log("Cannot connect"); } );

Immediately after "socket.open" the logger print only this message:
The operation could not be completed. Network is unreachable / console-via-logger.js:173

On Android, however, everything works perfectly.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.