blocshop / sockets-for-cordova Goto Github PK
View Code? Open in Web Editor NEWCordova plugin for socket network communication
Cordova plugin for socket network communication
Please help me with the above two questions.
Thanks a lot.
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)
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)
I am not sure if you can help me with this. But I have no clue what this problem produces. http://stackoverflow.com/questions/27882086/phonegap-cordova-socket-plugins-end-up-with-undefined-is-not-a-function-in-co
See pull request #14
Need any other modify?
Will be possible to also have udp sockets support?
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.
Running this on iOS my socket frequently gets stuck in the CLOSING state. Is there any way to destructively close a socket.
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.
Calling of shutdownWrite method on Socket object doesn't have any effect on wp8 platform.
_.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
Is it possible to open an ssh connection using this plugin?
Hi.
thanks for the plugin, can you also write how to use this plugin?
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();`
socket.write(data,function(res){alert("Data send Successfully")},function(err){console.log(err);alert(err)});
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
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.
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?
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).
Is there a way to force the socket.open through the Wifi even when the "Avoid bad WiFi Connections" is set. This setting allows internet requests to go out the 4g/3g if there is a non-internet device attached to WiFi.
How can I use ??? Have Example
Hello,
Thank you for this plugin. How I can use connect timeout parameter?
thank you.
Webview is unresponsive when socket is in opening state on Android platform.
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...
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
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
opening a local socket throws the below error
"Cannot register WP event dispatcher, Error: Missing Command Error"
Hi! What is the Licence for this project?
Thansk!
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
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!
Visual Studio don't load the plugin because the ns android is missing in plugin.xml
Add the ns to plugin node.
xmlns:android="http://schemas.android.com/apk/res/android"
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.
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?
Visual Studio 2015, the error is received on trying to add the custom plugin.
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
Could the programmers put a timeout in socket?
http://stackoverflow.com/questions/4969760/setting-a-timeout-for-socket-operations
Thanks
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
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?
I haven't tried this plugin yet... does this work on a chrome browser on a PC?
I like your plugin, but I am trying to figure out if a socket is connected already before trying to open a new one. Can you tell me how this would work?
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?
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.
When opening the socket, it closes automatically, has it happened to someone?
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
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!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.