I'm using simple Websocket connection on react native framework, with ios it works great, but on Android I'm in 70% getting message: WebSocketEvent {type: "error", message: null} and this error is closing socket connection. I don't know why does it happenning?
My code is:
self._ws = new WebSocket("wss://fe01-ws.wearetv.com/platform/simchacr/some_code");
var initPing = function (){
pingInterval = setInterval(function(){
ping.timestamp = new Date().getTime();
ping.sequenceNumber++;
ping.params.timestamp = ping.timestamp;
ping.params.sent_ts = ping.timestamp;
ping.params.seq = ping.sequenceNumber.toString();
self._ws.send(JSON.stringify(ping.params));
console.log("Ping is sent");
isPinged = false;
pongTimeout = setTimeout(function(){
if (isPinged === false) {
self._ws.close();
}
}, PONG_DELAY);
}, PING_INTERVAL);
};
var initConnection = (function me() {
isPinged = false;
self._ws.onopen = function () {
console.log("Connection opened");
initPing();
};
self._ws.onerror = function(error) {
console.error(error);
self._ws.close();
};
self._ws.onclose = function() {
console.log("Connection closed");
clearInterval(pingInterval);
clearTimeout(pongTimeout);
clearTimeout(reconnectTimeout);
reconnectTimeout = setTimeout(function(){
console.log("Ping reconnection");
initConnection();
initPing();
}, PING_RECONNECT_TIME);
isPinged = false;
};
self._ws.onmessage = function (message) {
//var data = JSON.parse(message.data);
//console.log(data);
//if (data[REQUEST_PROPERTY_MAIN] === "ACK") {
// clearTimeout(pongTimeout);
// clearTimeout(reconnectTimeout);
// isPinged = true;
//}
//self._getMessage(data);
};
return me;
})();
Have you configured Gradle to compile the same react-native version as the one you installed from the npm?
For example: compile project(':ReactAndroid')
as opposed to com.facebook.react:react-native:0.12.+
Related
I Making a chess app with react native, i sending & receiving my request with websocket,
when i run my app in ios every thing is ok,but when i run my app in android the web socket not open and return " Expected HTTP 101 response but was '403 Forbidden' ".
my create game code :
createGame() {
const { playConfig } = this.props;
fetch('https://en.lichess.org/setup/ai', {
method: 'POST',
headers: {
Accept: 'application/vnd.lichess.v2+json',
'Content-Type': 'application/json',
},
body: playConfig,
})
.then(res => res.json())
.then(this.onGameCreated);
}
onGameCreated = res => {
const { game } = this.state;
const socketUrl = res.url.socket;
const clientId = Math.random().toString(36).substring(2);
clearInterval(this.interval);
this.wsReady = false;
let url = `wss://socket.lichess.org${socketUrl}?sri=${clientId}&mobile=1`;
this.ws = new WebSocket(
url,
);
this.ws.onmessage = e => {
// a message was received
console.log(`received: ${e.data}`);
const data = JSON.parse(e.data);
let moveData;
let victor;
if (data.t === 'move' && data.v > game.history().length) {
moveData = data.d;
} else if (data.t === 'end') {
victor = data.d;
} else if (data.t === 'b') {
// b for batch
const first = data.d[0];
if (first) {
if (first.d.status && first.d.status.name === 'mate') {
moveData = first.d;
}
if (first.t === 'end') {
victor = first.d;
}
if (first.d.winner) {
victor = first.d.winner;
}
}
}
if (victor) {
dongSound.play();
this.setState({
victor,
});
this.ws = null;
} else if (moveData) {
const { uci, clock } = moveData;
const castle = moveData.castle;
let from = uci.substring(0, 2);
let to = uci.substring(2, 4);
if (castle && castle.king) {
from = castle.king[0];
to = castle.king[1];
}
this.board.movePiece(to, from);
if (clock) {
this.latestClock = clock;
}
}
};
this.ws.onerror = e => {
// an error occurred
console.log(e.message);
};
this.ws.onopen = () => {
this.wsReady = true;
dongSound.play();
this.setState({
initialized: true,
userColor: res.player.color === 'white' ? 'w' : 'b',
});
console.log('ws open');
// ping every second
this.interval = setInterval(
() => {
this.sendMessage({
t: 'p',
v: game.history().length,
});
},
1000,
);
};
};
any one has idea?
thank you in advance
Looks like you don't have permission to open a socket on this webserver.
I don't think the problem is in your Java code but the webserver configuration.
I am working on a ionic project and trying to use LokiJS. Below is my code,
controller,
$scope.test ={birthdays:[]};
$ionicPlatform.ready(function() {
BirthdayService.initDB();
BirthdayService.getAllBirthdays().then(function(birthdays){
console.log("birthdays=",birthdays);// gives empty array second run...
//var bday1 = {Name:"abrj",Date:new Date()};
//var bday2 = {Name:"abrj2",Date:new Date()};
//BirthdayService.addBirthday(bday1);
//BirthdayService.addBirthday(bday2); added birthdays during the first run.
});
});
I am using cordova-fs-adapter and cordova-file-plugin.
below is my service for adapter integration,
(function() {
angular.module('starter').factory('BirthdayService', ['$q', 'Loki', BirthdayService]);
function BirthdayService($q, Loki) {
var _db;
var _birthdays;
function initDB() {
var fsAdapter = new LokiCordovaFSAdapter({"prefix": "loki"});
_db = new Loki('birthdaysDB',
{
autosave: true,
autosaveInterval: 1000, // 1 second
adapter: fsAdapter
});
};
function getAllBirthdays() {
return $q(function (resolve, reject) {
var options = {
birthdays: {
proto: Object,
inflate: function (src, dst) {
var prop;
for (prop in src) {
if (prop === 'Date') {
dst.Date = new Date(src.Date);
} else {
dst[prop] = src[prop];
}
}
}
}
};
_db.loadDatabase(options, function () {
_birthdays = _db.getCollection('birthdays');
if (!_birthdays) {
_birthdays = _db.addCollection('birthdays');
}
resolve(_birthdays.data);
});
});
};
function addBirthday(birthday) {
console.log("Birthdays=",_birthdays);
_birthdays.insert(birthday);
};
function updateBirthday(birthday) {
_birthdays.update(birthday);
};
function deleteBirthday(birthday) {
_birthdays.remove(birthday);
};
return {
initDB: initDB,
getAllBirthdays: getAllBirthdays,
addBirthday: addBirthday,
updateBirthday: updateBirthday,
deleteBirthday: deleteBirthday
};
}
})();
In first run I am inserting two documents into the birthdays collections.On second run when I trying to check whether they have persisted, they weren't. I know I am doing something wrong.Do suggest.Local storage also gets cleared everytime i rerun(ionic run android)?!
We are customizing the DirectUpdate process as in the documentation (https://www-01.ibm.com/support/knowledgecenter/SSHS8R_7.1.0/com.ibm.worklight.dev.doc/dev/c_customizing_direct_update_ui_android_wp8_ios.html - with a directUpdateCustomListener) but in the onFinish callback the status is FAILURE_UNZIPPING.
I am testing on an Android (5.1.1) emulator.
function wlCommonInit(){
WL.Client.connect({
onSuccess: function() {
console.log("Successfully connected to Worklight Server.");
}, onFailure: function() {
console.log("Failed connecting to Worklight Server.");
}
});
}
var busyInd = new WL.BusyIndicator('content');
var savedDirectUpdateContext = null;
var restartDirectUpdate = function () {
if (savedDirectUpdateContext != null) {
savedDirectUpdateContext.start(directUpdateCustomListener); // use saved direct update context to restart direct update
}
};
var directUpdateCustomListener = {
onStart: function(totalSize) {
busyInd.show();
},
onProgress: function(status, totalSize, completeSize) {},
onFinish: function(status) {
busyInd.hide();
console.log("[MFP - DirectUpdate] Finish status: " + status);
var posSuccess = status.indexOf("SUCCESS");
if (posSuccess > -1) {
WL.Client.reloadApp();
} else {
WL.SimpleDialog.show('Update Failed', 'Press try again button', [{
text: "Try Again",
handler: restartDirectUpdate // restart direct update
}]);
wl_directUpdateChallengeHandler.submitFailure();
}
}
};
wl_directUpdateChallengeHandler.handleDirectUpdate = function(directUpdateData, directUpdateContext) {
savedDirectUpdateContext = directUpdateContext
WL.SimpleDialog.show('Update Avalible', 'Press Update button to download the new version!', [{
text : 'Update',
handler : function() {
directUpdateContext.start(directUpdateCustomListener);
}
}, {
text : 'Cancel',
handler : function() {
wl_directUpdateChallengeHandler.submitFailure();
}
}]);
};
How can we fix this?
The custom code is working fine without zxing installed. I suggest that you will try the same without this library. If it works, I suspect that it may be initializing or otherwise interfering with the Direct Update process once an update has been received.
Considering loading the library later in the app life cycle and see if this helps.
Firstly, sorry about my english; I am not a native speaker.
Secondly, I'm making an app for Android using the framework Ionic and I'm using Django as an REST API.
I have issues with a factory: the HTTP status from the request in Django is 200 and the database registers the change, but in the app the HTTP status is 0. This happens only in this factory that contains two POST requests. The other POST requests made on the other factories work fine.
To test the app I use Google Chrome (with the command --disable-web-security), Ionic version 1.5.0, Django version 1.8.2, Cordova version 5.0 (I couldn't find which version of AngularJS I'm using). I have the same issues on several mobile devices.
Here are 3 controllers that cause the problem:
.controller('PlanesCtrl', function($scope, $ionicModal, $ionicPopup,$location, Planes, $window) {
$scope.planes = JSON.parse($window.localStorage['planes']);
$scope.usuario = JSON.parse($window.localStorage['user']);
var usuario_id = {
codusuario: $scope.usuario["codusuario"]
};
$scope.mascotaEscogida = JSON.parse($window.localStorage['mascotaEscogida']);
var especie_id = {
codespecie: $scope.mascotaEscogida.codespecie
};
var mascota_id = {
codmascota: $scope.mascotaEscogida.id
};
var data = {
codespecie: $scope.mascotaEscogida.codespecie,
codmascota: $scope.mascotaEscogida.id
}
$scope.ver_plan = function(plan){
Planes.selectChosenPlan(plan.id);
if (plan.suscrito == 0){
$location.path("/app/planes/" + plan.id);
}
else{
$location.path("/app/entrenar/" + plan.id);
}
};
})
.controller('PlanCtrl', function($scope, $ionicModal,$location, $ionicPopup, $window, Planes) {
$scope.mascotaEscogida = JSON.parse($window.localStorage['mascotaEscogida']);
var mascota_id = {
codmascota: $scope.mascotaEscogida.codmascota
};
$scope.plan = JSON.parse($window.localStorage['planActual']);
var data = {
codplan: $scope.plan.id,
codespecie: $scope.mascotaEscogida.codespecie,
codmascota: $scope.mascotaEscogida.id
};
$scope.suscribir = function(){
var data = {
codplan: $scope.plan.id,
codespecie: $scope.mascotaEscogida.codespecie,
codmascota: $scope.mascotaEscogida.id
};
console.log($scope.plan.id);
console.log($scope.mascotaEscogida.codespecie);
console.log($scope.mascotaEscogida.id);
Planes.suscribir(data, function() {
alert("Su mascota ha sido suscrita al plan con éxito");
} , function() {
} , function() {
console.log("No funciona suscribir en funcion suscribir, PlanCtrl");
});
Planes.buscar(data, function() {
} , function() {
} , function() {
console.log("No funciona buscar en funcion suscribir, PlanCtrl");
});
$location.path("/app/pet/" + mascota_id);
$window.location.reload(true);
};
})
.controller('PetCtrl', function($scope, $stateParams, $filter, $location, Mascota, Planes, $window, $ionicModal) {
$scope.mascotaEscogida = JSON.parse($window.localStorage['mascotaEscogida']);
$scope.usuario_logged = JSON.parse($window.localStorage['user_data']);
$scope.usuario_info = JSON.parse($window.localStorage['user']);
var data = {
codespecie: $scope.mascotaEscogida.codespecie,
codmascota: $scope.mascotaEscogida.id
}
$scope.ver_entrenamientos = function(mascota){
Planes.buscar(data, function() {
alert("Planes encontrados con exito");
} , function() {
alert("La mascotas no posee especie registrada (esto es muy extraño)");
} , function() {
console.log("No funciona buscar en ver_entrenamientos, PetCtrl");
});
$location.path("/app/planes");
$window.location.reload(true);
};
if($scope.usuario_logged === false) {
$location.path('/login');
}
else {
$scope.test = function() {
fecha_hora = $filter('date')(new Date(), 'yyyy-MM-dd HH:mm:ss', '-0300');
var info = {
fecha: fecha_hora,
codmascota: $scope.mascotaEscogida.id,
codusuario: $scope.usuario_info.codusuario
}
Mascota.alimentar(info, function() {
alert("La mascota ha sido alimentada con exito :)");
} , function() {
alert("Lo sentimos, algo ha ocurrido y no podemos registrar la alimentación");
} , function() {
alert("Verifica la conexión a internet");
});
}
}
})
And here is the factory:
.factory("Planes", function($http, $window){
var url = "http://localhost:8000/plan/";
var currentPlanes = function(data){
$window.localStorage['planes'] = JSON.stringify(data);
};
return {
selectChosenPlan: function(id) {
var arregloPlanes = JSON.parse($window.localStorage['planes']);
for (var i = 0; i <= arregloPlanes.length - 1; i++) {
if (parseInt(arregloPlanes[i].id) == id) {
$window.localStorage['planActual'] = JSON.stringify(arregloPlanes[i]);
}
}
},
buscar: function(inf, successFunction, errorFunction, connectionError) {
$http({
method: 'POST',
url: url + 'planes/',
headers: {'Content-Type': 'application/json'},
data: JSON.stringify(inf),
timeout: 20000
}).then(function successCallback(response) {
if (response.data.length > 0) {
console.log("buscar" + response.data[0]);
currentPlanes(response.data);
successFunction();
}
else{
currentPlanes(response.data);
errorFunction();
}
}, function errorCallback(response) {
connectionError();
});
},
suscribir: function(inf, successFunction, errorFunction, connectionError) {
$http({
method: 'POST',
url: url + 'suscribir/',
headers: {'Content-Type': 'application/json'},
data: JSON.stringify(inf),
timeout: 20000
}).then(function successCallback(response) {
if (response.data.length > 0) {
console.log("suscribir" + response.data[0]);
currentPlanes(response.data);
successFunction();
}
else{
currentPlanes(response.data);
errorFunction();
}
}, function errorCallback(response) {
connectionError();
});
}
};
})
I've made some research in the internet, but all the solutions I've found point to the CORS. If that were the problem, the other factory wouldn't work either, so I don't think that's the problem. Some other answers say that the problem could be in the HTML, on the button that calls 'ver_plan' or 'ver_entrenamiento', but both are set with type="button", so the submit wasn't the problem either. The error happens randomly and I can't find the issue in the flow of events. Sometimes, I even get a 'broken pipe' message from Django, but this also happens randomly.
I know that the JSON answer is valid and has the correct format; I'm out of ideas and I need to solve these issues.
Edit: Also, the line console.log("No funciona buscar en funcion suscribir, PlanCtrl"); doesn't appear in the console when I get the problem.
I found the answer a couple of weeks ago. The problem was
$window.location.reload(true); and $location.path();
It is not necessary the line $window.location.reload(true); if $location.path(); is located inside the factory call. For example:
Planes.buscar(data, function() {
$location.path("/app/pet/" + mascota_id);
} , function() {
} , function() {
console.log("No funciona buscar en funcion suscribir, PlanCtrl");
});
This way, the redirection occurs only if the answer from the server was successful and there is no need to use $window.location.reload(true);
I wish I can give you more details about the reason of the problem but my english is not good enough.
I'm trying to create a Cordova app that will be able to handle more than one touch event simultaneously.
So the user can continue to touch a button while moving a slider, or touching other buttons.
The app will only run on Android, and more precisely Android 4.1.2 or more. I'm using Cordova 3.1.0.
For now, I'm doing the following with no luck:
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
app.handleSerial();
},
handleSerial: function() {
var tht = document.getElementById('manuel');
var speed1 = document.getElementById('rythme');
var speed2 = document.getElementById('melodie');
var speed3 = document.getElementById('sequenceur');
tht.addEventListener('touchstart', function(event) {
serial.write('1');
}, false);
tht.addEventListener('touchend', function(event) {
serial.write('0');
}, false);
speed1.addEventListener('touchstart', function(event) {
serial.write('2');
}, false);
speed2.addEventListener('touchstart', function(event) {
serial.write('3');
}, false);
speed3.addEventListener('touchstart', function(event) {
serial.write('4');
}, false);
var errorCallback = function(message) {
alert('Error: ' + message);
};
serial.requestPermission(
function(successMessage) {
alert(successMessage);
serial.open(
{baudRate: 9600},
function(successMessage) {
alert(successMessage);
},
errorCallback
);
},
errorCallback
);
}
};
But it's not working, while tht button is touched I cannot touch other buttons in order to handle their events.
Any idea?
Thanks!
Ended up doing this, where buttons is the closest common ancestor. Works nice.
var buttons = document.getElementById('buttons');
buttons.addEventListener('touchstart', function(event) {
for (var i = 0; i < event.touches.length; i++) {
var touch = event.touches[i];
var elem = document.elementFromPoint(touch.pageX, touch.pageY);
switch (elem.id) {
case 'manuel':
serial.write('1');
break;
case 'rythme':
serial.write('2');
break;
case 'melodie':
serial.write('3');
break;
case 'sequenceur':
serial.write('4');
break;
}
}
});
buttons.addEventListener('touchend', function(event) {
var contains = false;
for (var i = 0; i < event.touches.length; i++) {
var touch = event.touches[i];
var elem = document.elementFromPoint(touch.pageX, touch.pageY);
if (elem.id === 'manuel') contains = true;
}
if (!contains) serial.write('0');
});