Hi,
I want to make tcp socket client on ionic. So I found https://github.com/nutella/ionic-cordova-chrome-tcp-example.
My problem is " TypeError: Cannot read property ‘tcp’ of undefined"
It seems not to create “chrome.sockets”. and in my html, I added below script as sample but not thing logged.
<script type="text/javascript">
document.addEventListener('deviceready', function onDeviceReady() {
console.log(chrome);
angular.bootstrap(document, ['starter']);
}, false);
</script>
In my test, I added just the ng-cordova.min.js and cordova plugin add cordova-plugin-chrome-apps-sockets-tcp …
I’m testing this with browser by issuing ionic serve.
I don’t have any clue to fix this. Below code almost similar. But If I wrong, Please let me know.
App.js is
angular.module('starter', ['ionic', 'starter.controllers','ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
})
My controller is
angular.module('starter.controllers', [])
.controller('TcpCtrl', function($scope,tcpServices) {
var vm= this;
vm.send= send;
init();
function init() {
vm.result= '';
}
$scope.test=function(){
tcpServices.sendPacket("127.0.0.1",1234,"abcd").then(function(data) {
vm.result= data;
});
}
})
My service.js
angular.module('starter').factory('tcpServices', tcpServices);
tcpServices.$inject= ['$q'];
function tcpServices($q) {
console.log("here tcpServices");
function 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;
}
function 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;
}
function sendPacket(ipAddr,ipPort,data) {
console.log("here tcpServices' sendPacket",ipAddr,ipPort);
var delay= 5000; /// 5 seconds timeout
var deferred= $q.defer();
chrome.sockets.tcp.create({}, function(createInfo) {
var _socketTcpId= createInfo.socketId;
chrome.sockets.tcp.connect(_socketTcpId, ipAddr, ipPort, function(result) { // <-- Error
if (result === 0) {
var data2send= str2arrayBuffer(data);
/// connection ok, send the packet
chrome.sockets.tcp.send(_socketTcpId, data2send);
}
});
chrome.sockets.tcp.onReceive.addListener(function(info) {
/// recived, then close connection
chrome.sockets.tcp.close(_socketTcpId);
var data= arrayBuffer2str(info.data);
deferred.resolve(data);
});
/// set the timeout
setTimeout(function() {
chrome.sockets.tcp.close(_socketTcpId);
deferred.reject();
}, delay);
});
return deferred.promise;
}
return {
sendPacket: sendPacket
};
};