Why Websocket connection is disconneting after sending message on iOS 15 devices? - javascript

I am building a website based on web socket communication. Its is working fine until iOS 14 but started breaking from iOS 15. Web socket java script client is able to open connection to server, but upon trying to send a message, the connection is getting closed. Following is my html and JS code.
function start_websocket() {
connection = new WebSocket("wss://localhost/wss/");
connection.onopen = function () {
console.log('Connection Opened');
};
connection.onerror = function (error) {
console.log('WebSocket Error ' + error);
};
connection.onclose = function(){
console.log("Closed");
};
connection.onmessage = function (e) {
console.log("Message Received :" + e.data);
};
}
function myFunction() {
var testText = document.getElementById("testText");
if (testText.value != "" && connection.readyState === connection.OPEN) {
connection.send("Test");
}
}
start_websocket();
myFunction() is an on-click event of a button.
A Java Websocket server is used, which will decode and send the messages based on the Data framing in https://datatracker.ietf.org/doc/html/rfc6455#section-5.
Saw different articles on the Web, but didn't found a solution to this issue. Any suggestions are much appreciated. Looking forward for your answers
Thanks in advance.

Related

Execute a function when a nodejs event is received

I might missing something basic, but here is my goal: I have a small instant chat example based on tutorial found here Instant Chat for drupal
The principle is to connect to a nodejs server that basically just broadcast all messages it receives.
I have this function on the client side (inside a drupal tpl.php file):
(function($) {
var myNick = 'me';
var socket = io.connect('http://<?php print $_SERVER['SERVER_ADDR'] ?>:8081');
socket.on('connect', function() {
$('#chat').addClass('connected');
});
socket.on('user message', message);
function message(from, msg) {
if (msg == 'GO') {
** EXECUTE A FUNCTION HERE **
} else { //display the message and sender
$('#lines').append($('<p>').append(from, msg));
}
}
$(document).ready(function() {
$('#send-message').submit(function() {
message(myNick, $('#messageinput').val());
socket.emit('user message', $('#messageinput').val());
clear();
$('#lines').get(0).scrollTop = 10000000;
return false;
});
function clear() {
$('#message').val('').focus();
};
});
})(jQuery);
When I send a message with content =GO, the submit is executed, the message(..,..) function is called and my specific function is executed properly.
But when I receive a GO message, the socket.on event triggers, message() function is called, but my specific function is NOT executed.
Any Idea how I can fix this?
Many thanks for your help.
Michael.

How to communicate between multiple windows of same chrome apps

I have a packaged chrome app having multiple windows. For example if I click a button in first window then a second window opened. Now how to send messages or commands to each other.
I have read a lot about it but did not figure out as i am very much new to this.
Any sample code will be very helpful.
There is a existing question How to communicate between multiple windows of the same chrome app?, but did not understand how to do it.
Thanks in advance!!!
You can use the postmessage method of a window, in order to send information to another window. By following this approach, you can execute a method from a window (A) on a different window (B). You'll need to create an event on window B that will inform A that the method ran correctly.
The code would be something like:
Sender:
//create popup window
var domain = 'http://scriptandstyle.com';
var myPopup = window.open(domain + '/windowPostMessageListener.html','myWindow');
//periodical message sender
setInterval(function(){
var message = 'Hello! The time is: ' + (new Date().getTime());
console.log('blog.local: sending message: ' + message);
myPopup.postMessage(message,domain); //send the message and target URI
},6000);
//listen to holla back
window.addEventListener('message',function(event) {
if(event.origin !== 'http://scriptandstyle.com') return;
console.log('received response: ',event.data);
},false);
Destination:
//respond to events
window.addEventListener('message',function(event) {
if(event.origin !== 'http://davidwalsh.name') return;
console.log('message received: ' + event.data,event);
event.source.postMessage('holla back youngin!',event.origin);
},false);
You can also find an in-dept explanation here: http://davidwalsh.name/window-postmessage
In the case of a Chrome app, the part about the domain is not required.
You need something as:
targetWindow = chrome.app.window.get("window-id").contentWindow;
targetWindow.postMessage(message, "*");
to send a message, while to receive:
window.addEventListener('message', function(event) {
var windowId = chrome.app.window.current().id;
console.log(windowId + ': received a message: ' + event.data, event);
var message = 'hello back!';
console.log(windowId + ': sending message: ' + message);
event.source.postMessage(message, event.origin);
});

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.

Phonegap GaPlugin refusing connection

So I installed the plugin for phonegap to run google analytics. I set it up using plugman, no issues. However I am unable to establish a connection to google analytics.
document.addEventListener("deviceready", function(){
console.log('device ready');
config.gaPlugin = window.plugins.gaPlugin;
config.gaPlugin.init(console.log('ga plugin inititalized'), console.log('ga plugin failed'), config.analyticsCode, 1);
}, false);
And Instead of getting a connection back I get one response of
W/GAV2(12581): Thread[WebViewCoreThread,5,main]: Need to call initialize() and be in fallback mode to start dispatch.
I thought the init function was the initialize? However as I set it every 5 seconds the connection gets refused.
W/GAV2(12581): Thread[GAThread,5,main]: Connection to https://ssl.google-analytics.com refused
W/GAV2(12581): Thread[GAThread,5,main]: Exception sending hit: HttpHostConnectException
I have no idea what to do next, I've seen reference of needing to modify the errorhandling calls to not look for an https request, but I would like to hope its just an error in my code or a configuration error. Anyone have insight?
I use the following code which works with GAPlugin
gaInit: function() {
gaPlugin.init(gaSuccessConnect, gaFail, "UA-XXXXXX-3", 10);
},
gaSuccess: function() {
console.log('Successfully connected to Google Analytics');
},
gaSuccessConnect: function() {
console.log('Successfully initiated connection to Google Analytics');
gaTrackPage();
},
gaFail: function() {
console.warn("Failed to connect to Google Analytics");
},
gaTrackPage: function() {
gaPlugin.trackPage(gaSuccess, gaFail, "index.html");
console.log('Tracking index');
},
gaTrackPageView: function(page) {
var index = "index.html";
var trackpage = index.concat(page);
console.log('Tracking ' + page);
gaPlugin.trackPage(gaSuccess, gaFail, trackpage);
},
and call gaInit from onDeviceReady.

Reconnect hub necessary

I have simple project in ASP.NET Web site with signalr.
Code for start connection hub:
var scriptStarted = 'var myHub = $.connection.' + hubName + ';' + methodNameInitHub + '(myHub);';
$.connection.hub.error(function () {
alert("An error occured");
});
$.connection.hub.start()
.done(function () {
eval(scriptStarted);
myHub.server.registerClient($.connection.hub.id, clientIdentifier);
})
.fail(function () { alert("Could not Connect!"); });
This method is call in "methodNameInitHub + '(myHub);"
function methodInitEventHub(hub) {
if (hub) {
hub.client.addEvent = function (eventOperationName, eventType) {
$("#events").append("<li>" + eventOperationName + ", " + eventType + "</li>");
};
}
}
Code for stop connection hub:
$.connection.hub.stop();
When I load .aspx page and start hub all code execute without errors, but event from server not recieved.
After I stop and start again hub connection events begining received in client (browser)
http://clip2net.com/s/2CP2e
Why I need to restart connection hub for begin received event from server ?
Thanks.
The reason you're having issues is because you must have at least 1 client side hub function prior to calling start otherwise you will not be subscribed to the hub.
Try doing
myHub.client.foo = function() {}
prior to start.
The reason why it works after you stop then re-start the connection is because your script binds a new client method, hence allowing you to subscribe to the hub after you've restarted the connection.
Hope this helps!

Categories