Socket.io does not work in mobile-Android - javascript

I built a simple snake game by javascript-socket.io, it works in desktop nicely, but don't work in mobile(android).
and i don't know why?
error log in chrome browser in mobile:
my project link:
https://hamed8993.github.io/front
if you go to above link, you will see that it works in Desktop as we want,
but if go by Mobile(Android) will see that it do not works!
there are codes:
1)socket.io version : "socket.io": "2.3.0"
2)index.js module in back-End (that runs Socket.io for run snake Game in front-End):
const io = require("socket.io")();
io.on("connection", client => {
client.emit("init", { data: "Game Started!"})
startGameInterval(client);
});
function startGameInterval(client){
const intervalId = setInterval(() => {
client.emit("palse")
}, 400)
}
io.listen(3000);
3)index.js (for client page of index.html):
window.onload = () => {
//socket.io:
const socket = io("http://127.0.0.1:3000");
socket.on("init", (msg)=> console.log(msg) );
socket.on("palse", update);
// other functions, and "update" function...
}
this project Repository Address in gitHub:
https://github.com/hamed8993/hamed8993.github.io

Related

Expo App keeps crashing on Android while trying to navigate

I have an expo managed app with a button on the screen, when the button is pressed several API calls are made to my backend and finally after the last API call depending on whether the Platform OS is ios or android i would like the app to navigate to a specific screen.
On IOS, everything is working accordingly.
On Android, the expo app crashes and closes before navigating to the next screen.
Here is my onButtonClick function:
const handlePayment=async()=>{
setLoading(true);
const sessionResponse = await paymentApi.paymentSession(
selected,route.params.transaction.id,cvv
);
if(!sessionResponse.ok){
setLoading(false)
if(sessionResponse.data){
Alert.alert(sessionResponse.data.error)
}else{
Alert.alert("Unexpected Error Occurred while creating session.")
}
}
console.log('create and update session',sessionResponse)
if(sessionResponse.data.session.updateStatus==='SUCCESS'){
const initiateResponse = await paymentApi.initiateAuthentication(
sessionResponse.data.session.id,route.params.transaction.id
);
if(!initiateResponse.ok){
setLoading(false)
if(initiateResponse.data){
Alert.alert(initiateResponse.data.error)
}else{
Alert.alert("Unexpected Error Occurred while initiating authentication")
}
}
console.log('Initiate Authentication',initiateResponse.data);
if(initiateResponse.data.result==='SUCCESS'){
setInitiateWebView(true);
const redirectHTML=(initiateResponse.data.authentication.redirectHtml).replace(/\\/g, '');
setInitiateWebViewUrl(redirectHTML);
console.log('session id ', sessionResponse.data.session.id)
const authenticateResponse = await paymentApi.authenticatePayer(
sessionResponse.data.session.id,route.params.transaction.id
);
if(!authenticateResponse.ok){
setLoading(false)
if(Platform.OS !== 'ios'){
clearInterval(myInterval)
}
Alert.alert("Unexpected Error Occurred","Please try again")
}
console.log('authenticate payer',authenticateResponse.data)
const authenticationResponseData = authenticateResponse.data;
console.log('authenticate payer authenticate data',authenticationResponseData.authentication);
const payerInteraction = authenticationResponseData.authentication.payerInteraction;
if(authenticationResponseData.authentication['3ds2']){
const status = authenticationResponseData.authentication['3ds2'].transactionStatus;
if(payerInteraction==='REQUIRED'&&status==="C"){
console.log("Challenge Flow")
setAuthenticateWebViewUrl(authenticationResponseData.authentication.redirectHtml.replace(/\\/g, ''))
console.log('Auth webview url::::::',authenticationResponseData.authentication.redirectHtml.replace(/\\/g, ''))
----> this is the last thing that appears on console before android app crashes
if(Platform.OS==='ios'){
setLoading(false);
navigation.navigate(routes.PAYWITHTOKEN,{html:authenticationResponseData.authentication.redirectHtml.replace(/\\/g, '')})
}else {
setLoading(false);
navigation.navigate(routes.PAYWITHTOKENANDROID)
}
}
The other screen is just a blank screen. I have tried navigating to that screen somewhere else inside my app and its working. The problem is here.
Follow instructions for watch logcat:
Open android studio

cant click the button (electron)

im try to do a project that connect pc to pc like screencast. when following the coding online im having a problem when trying to click the button. i cant click the button to pup up the id code.
This the code for app.js
const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const { v4: uuid4} = require('uuid');
const screenshot= require('screenshot-desktop');
var socket = require('socket.io-client')('http://172.20.10.3:5000');
var interval;
const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 500,
height: 150,
webPreferences: {
preload: path.join(__dirname, 'index.js')
}
})
// and load the index.html of the app.
mainWindow.removeMenu();
mainWindow.loadFile('index.html')
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0)
createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin')
app.quit()
})
ipcMain.on("start-share", function(event , arg){
var uuid = uuid4();
socket.emit("join-message", uuid);
event.reply("uuid", uuid);
})
ipcMain.on("stop-share", function(event, arg){
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
This is the index.js file
const ipcRenderer = require ('electron').ipcRenderer;
window.onload = function(){
ipcRenderer.on("uuid", (event, data)=>{
document.getElementById("code").innerHTML = data;
})
}
function startShare(){
ipcRenderer.send("start-share", {} );
document.getElementById("start").style.display = "none";
document.getElementById("stop").style.display = "block";
}
function stopShare(){
ipcRenderer.send("stop-share", {});
document.getElementById("stop").style.display = "none";
document.getElementById("start").style.display = "block";
}
this is the popup when running the code. i cant click the start button
enter image description here
im following this video from (youtube)
this the documentation that i follow in electronelectron website
if someone having problem to see the codes i will try to edit and insert more code or maybe send a zip file. im really needed some help in developed this project for education purpose
im expecting some guide to develop this project. if can i would like the same in the video but i have follow that video from start to end but stuck in the middle of the video. really needed the help
It seems you didn't add your startShare and stopShare functions to your index.html. The preload script is used only for a bridge between your main process and ui process. It doesn't have window object and doesn't attach itself to the index.html.
webPreferences: {
preload: path.join(__dirname, 'index.js')
}
You have to create a bridge and pass ipcRenderer.on function to your ui process. Or you also can add nodeIntegration: true to your webPreferences object. You can read some disadvantages about it.
Then you need to attach your index.js file to the index.html using <script> tag.

setInterval running more times than intended?

I have an application written in node.js using socket.io. The main event loop looks like this:
io.on("connect", function(CLIENT) {
//Run this code when a client connects
SERVER.connectPlayer(CLIENT);
//Recieve input from client
SERVER.handleInput(CLIENT);
//Run this code when a client disconnects
CLIENT.on("disconnect", function() {
SERVER.disconnectPlayer(CLIENT);
});
});
function main() {
SERVER.update();
}
setInterval(main, SERVER.tickRate);
This works fine, but I'm having an issue with SERVER.handleInput:
//Recieve input from the client
Server.prototype.handleInput = function(client) {
client.on("sendKey", function(data) {
client.player.handleKey(data.key, data.pressed);
});
client.on("sendMouse", function(data) {
client.player.mouse_x = data.x;
client.player.mouse_y = data.y;
});
}
Both of these work fine, but the second method client.on("sendMouse") triggers my main() loop above whenever it is run. I've tried commenting out the body of sendMouse but that doesn't change anything.
This method is being triggered by the client whenever the user moves the mouse. This is the code I'm using:
//Handles input on the client and sends it to the server
Game.prototype.bindKeys = function() {
var game = this;
this.input = {};
document.addEventListener("mousemove", function(event) {
game.mouseMove(event);
}, false);
}
Game.prototype.mouseMove = function(event) {
this.setMousePos(event);
client.emit("sendMouse", this.mouse);
}
setMousePos just figures out the current position of the cursor and sets it so that the client knows what coordinates to send back to the server. If I remove sendMouse on the client the game runs perfectly but otherwise my main setInterval loop is being run additionally every time sendMouse triggers.
I have no idea what would cause this. The keyboard input works perfectly fine. I'd greatly appreciate any advice.

ResizeObserver don't work as expected on Windows

I was playing with ResizeObserver (that's supported by google chrome behind experimental web platform flag). I've create codepen demo using jQuery UI resizable. It work fine on chromium linux, but on Windows it stops after a while or execute only once.
My code look like this:
$('#node').css({
width: 140,
height: 50
}).resizable();
function resizer(node, callback) {
if (window.ResizeObserver) {
var resizer = new ResizeObserver(function(entries) {
callback(entries[0]);
});
resizer.observe(node);
return () => resizer.unobserve(node);
} else {
return () => undefined;
}
}
resizer(document.querySelector('.content'), function(entry) {
var width = entry.contentRect.width;
var height = entry.contentRect.height
console.log(width + 'x' + height);
// custom event found on
// https://ebidel.github.io/demos/dom_resize_events.html
entry.target.dispatchEvent(new CustomEvent('resize', {
detail: {width,height}
}));
});
document.querySelector('.content').addEventListener('resize', (e) => {
console.log(e.detail);
});
I've try to restart the browser, close/open developer tools also download the files to local drive and open using file protocol and got the same results.
the google chrome example works fine,
Here is a my pen
It seems that the observer get Garbage Collected, adding
var r;
...
function resizer(node, callback) {
...
var resizer = new ResizeObserver(...);
r = resizer;
...
}
solved the issue

Firefox OS alarm to wake up closed app

Looking at documentation it looks like the alarm api can be used to restart an app at a certain time
I changed the code from boilerplate example in this way
// Alarm API
var alarmDate = new Date("Jul 8, 2014 19:35:00"),
addAlarm = document.querySelector("#add-alarm"),
alarmDisplay = document.querySelector("#alarm-display");
if (addAlarm) {
addAlarm.onclick = function () {
var alarm = navigator.mozAlarms.add(alarmDate, "honorTimezone", {
"optionalData" : "I am data"
});
alarm.onsuccess = function () {
var request = window.navigator.mozApps.getSelf();
request.onsuccess = function() {
navigator.mozSetMessageHandler("alarm", function (mozAlarm) {
request.result.launch();
alert("alarm fired: " + JSON.stringify(mozAlarm.data));
});
};
request.onerror = function() {
alert("Error: " + request.error.name);
};
};
The code seems to bring up the app only if the app is running (even in background) BUT not if the app is closed.
Is this the intended behaviour? Any way to restart a closed app?
Also is it possible to bring up the app in foreground and make it unlock the screen?
Thanks
UPDATE
Just as a clarification, the issue appears when the system memory load requires killing an app. Android provides a way to schedule restart of an app (while iOS, afaik, does not...).
It would be useful if an app could be restarted at the moment in which it's required.
That's also saving a lot of battery...
Your code is wrong: the setMessageHandler is created in the onsuccess handler of mozAlarms.add. That code will not be executed when the alarm fires. You need to always add the listener on app startup.
Here's some simple code that adds and responds to an alarm (from app-days-dhaka).
var request = navigator.mozAlarms.add(new Date((+new Date()) + 30000), 'ignoreTimezone', {
type: 'yolo'
});
console.log('setting to', new Date((+new Date()) + 30000) + '')
request.onsuccess = function() {
console.log('success');
}
request.onerror = function() {
console.error('err');
}
navigator.mozSetMessageHandler('alarm', function() {
console.log('alarm');
launchSelf();
});
function launchSelf() {
var request = window.navigator.mozApps.getSelf();
request.onsuccess = function() {
if (request.result) {
request.result.launch();
}
};
}
Open the app (this will set the alarm), then close the app immediately (via long press on home). After 30 seconds the app will open again automatically.

Categories