For one of my project using Ionic 2, I’ve to connect to a server using TCP/IP protocol.
Such as if I use Netcat to connect to host:post to send and receive messages.
I’ve read the documentation but I think there’s no module do to it ? I’ve anyone an idea how I can proceed ?
Thank you for your reply !
I’ve already see your exemple but problem is that I don’t know how to load the plugin with Ionic 2, app return undefined error when I try to use it…
I’ve also try with https://github.com/blocshop/sockets-for-cordova, I can connect and send a message but I think that events onData, onError, onClose are never fired…He’s maybe no more updated !
And if you want to debug, use adb logcat or use chrome DevTools to link to your device (Android I use) to see the logs and any other complaints the plugin gives
Thanks a lot ! I can now use it, connect to TCP server and send a message but I’m getting a time out, there’s no return data…
It’s maybe a problem with the server !
import { Injectable } from ‘@angular/core’;
import { Http } from ‘@angular/http’;
import ‘rxjs/add/operator/map’;
@Injectable()
export class TcpServicesProvider {
constructor(public http: Http) {
console.log('Hello TcpServicesProvider Provider');
}
arrayBuffer2str(buf) {
var str= '';
var ui8= new Uint8Array(buf);
for (var i= 0 ; i < ui8.length ; i++) {
str= str+String.fromCharCode(ui8[i]);
}
return str;
}
str2arrayBuffer(str) {
var buf= new ArrayBuffer(str.length);
var bufView= new Uint8Array(buf);
for (var i= 0 ; i < str.length ; i++) {
bufView[i]= str.charCodeAt(i);
}
return buf;
}
sendPacket(ipAddr,ipPort,data) {
console.log("from TcpServicesProvider")
var delay= 5000; /// 5 seconds timeout
(<any>window).chrome.sockets.tcp.create({}, createInfo => { //callback function with createInfo as the parameter
var _socketTcpId= createInfo.socketId;
(<any>window).chrome.sockets.tcp.connect(_socketTcpId, ipAddr, ipPort, result => { //callback function with result as the parameter
if (result === 0) {
var data2send= this.str2arrayBuffer(data);
/// connection ok, send the packet
(<any>window).chrome.sockets.tcp.send(_socketTcpId, data2send);
}
});
(<any>window).chrome.sockets.tcp.onReceive.addListener( info => { //callback function with info as the parameter
/// recived, then close connection
(<any>window).chrome.sockets.tcp.close(_socketTcpId);
var data= this.arrayBuffer2str(info.data);
});
/// set the timeout
setTimeout(function() {
(<any>window).chrome.sockets.tcp.close(_socketTcpId);
}, delay);
});
}
This is the code I tried to use TCP sockets in ionic
but it returned error (can’t find property ‘sockets’ of undefined). I used “npm install cordova-plugin-chrome-apps-sockets-tcp --save”. but i still don’t know how to work with this plugin.