SignalR 2 - Pending AJX requests after opening multiple tabs - ajax

I'm using SignalR 2 and I'm having problems when I open multiple tabs of the same page. After opening 4 or 5 tabs, all the requests get in pending status, like if I had exceeded the maximum allowed by the browser. If I close a few tabs, everything works again. Even with all the tabs opened, if I open a different browser it works. This happens both in Chrome and Firefox. If I disable SignalR, I can open as many tabs as I want.
This is my code:
// Reference the auto-generated proxy for the hub.
notificator.hub = $.connection.messageHub;
// Create a function that the hub can call back to display messages.
notificator.hub.client.refreshNotifications = function () {
// business code
};
$.connection.hub.start().done(function () {
notificator.hubStarted = true;
});
$.connection.hub.disconnected(function () {
notificator.hubStarted = false;
setTimeout(function () {
$.connection.hub.start();
}, 2000); // Restart connection after 2 seconds.
});
If I remove the handler for disconnected event, the problem persists. The notification system works correctly so SignalR is doing its job but it's causing me issues in the app. It's even slower.

I found two solutions:
1) In my case, it's an intranet web application so I know that everybody supports WebSockets and WebSockets doesn't have the connection limitation. But, why this was not working? well, first I added logging to SignalR by adding this line:
$.connection.hub.logging = true;
Then I tried to force using WebSockets:
$.connection.hub.start({ transport: 'webSockets' }).done(function () { .. });
But, checking the logs I found out that WebSockets were not supported because they were not installed in the server. So, I followed these steps in Windows 2012 and installed it:
Open Server Manager.
Under the Manage menu, click Add Roles and Features.
Select Role-based or Feature-based Installation, and then click
Next.
Select the appropriate server, (your local server is selected by
default), and then click Next.
Expand Web Server (IIS) in the Roles tree, then expand Web Server,
and then expand Application Development.
Select WebSocket Protocol, and then click Next.
Click Install.
Source: http://www.iis.net/learn/get-started/whats-new-in-iis-8/iis-80-websocket-protocol-support
After that, everything worked. In Chrome, under Network tab, you'll find a WS filter. Click on it and you should see the websocket.
2) Using IWC-SignalR:
https://github.com/slimjack/IWC-SignalR
It works this way:
One of the windows becomes a connection owner (choosen randomly) and
holds the real SignalR connection. If connection owner is closed or
crashed another window becomes a connection owner - this happens
automatically. Inter-window communication is done by means of IWC.

Related

OneSignal registration fails after refresh

I am using OneSignal in my Laravel/Vue app. I have included it within <head> as stated in documentation:
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(function() {
OneSignal.init({
appId: "{{ env('ONESIGNAL_APP_ID') }}"
});
OneSignal.showNativePrompt();
});
</script>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/OneSignalSDKWorker.js')
.then(function () {
console.log('Service worker registered');
})
.catch(function (error) {
console.log('Service worker registration failed:', error);
});
} else {
console.log('Service workers are not supported.');
}
</script>
I also have a service worker of my own, so I've followed the documentation here as well.
What is happening after a hard reset is that service worker gets installed and it is all fine, however once I refresh the page I am getting:
OneSignalPageSDKES6.js?v=151102:1 Uncaught (in promise) InvalidStateError: The current environment does not support this operation.
at Function.getServiceWorkerHref (https://cdn.onesignal.com/sdks/OneSignalPageSDKES6.js?v=151102:1:41510)
at xe. (https://cdn.onesignal.com/sdks/OneSignalPageSDKES6.js?v=151102:1:144028)
at Generator.next ()
at r (https://cdn.onesignal.com/sdks/OneSignalPageSDKES6.js?v=151102:1:716)
And I have no idea what does that mean? What is "current environment"? Where to start debugging? I've tried putting console logs around it, however it led me nowhere...
You would start debugging by looking at the source code of the library.
In your case your library is the OneSignal SDK for browsers.
Let's do this!!!
We can see that this error is thrown by getServiceWorkerHref function (which is defined here) and the error message is driven by the InvalidStateReason enumeration:
case InvalidStateReason.UnsupportedEnvironment:
super(`The current environment does not support this operation.`);
break;
If you look at the first linked file, you will see the note on getServiceWorkerHref OneSignal developers left for the those who dare venture into their source code:
else if (workerState === ServiceWorkerActiveState.Bypassed) {
/*
if the page is hard refreshed bypassing the cache, no service worker
will control the page.
It doesn't matter if we try to reinstall an existing worker; still no
service worker will control the page after installation.
*/
throw new InvalidStateError(InvalidStateReason.UnsupportedEnvironment);
}
As you can see, the error is raised when the service worker has the "Bypassed" state. What is that, you may ask? Let's look at ServiceWorkerActiveState enumeration below, in the same file:
/**
* A service worker is active but not controlling the page. This can occur if
* the page is hard-refreshed bypassing the cache, which also bypasses service
* workers.
*/
Bypassed = 'Bypassed',
It seems, when the browser "hard-refreshes" the page, it bypasses the service worker and OneSignal can't properly initialize when that happens. Hard-refresh can happen for a number of reasons — here are some of them (to the best of my knowledge):
if you click the refresh button a bunch of times (usually seconds consecutive refresh within a short period of time may trigger this)
if you have caching disabled in your DevTools
if the server sets a no-cache header
What is happening after a hard reset
I don't know exactly what you mean by "hard reset", but that sounds like it would trigger this issue. I would suggest you close your browser and then visit the page you are working on without using "reset" functions — theoretically, the service worker should be used for caching on consecutive visits and that would ensure OneSignal can function.

Waiting on input from Socket in Xamarin Froms

GOAL
The application needs to constantly read from a socket - and when it receives a line that is not empty it needs to do an appropriate action.
Issue
From what I researched you can't do services in Xamarin Forms, since each service is platform dependent. (IOS, Andoird, Windows). So what I am looking for as a way to constantly monitor inputs from a Bluetooth port in this case, simply by calling a already defined function.
Tried
I tried using a Refresh view. But there were issues with that from a code point of view and a visual point of view.
Current Code
This is what I have tried, but unfortuntately it has mixed results. The socket seems to connect when first pairing but then closed if I try to read:
Device.StartTimer(TimeSpan.FromMilliseconds(miliseconds), () =>
{
command.Execute(null);
return true;
});

Keep Connection with Socket.io

I'm trying to connect at asterisk websocket, using socket.io-client
socket = io.connect(url ,{
transports: ['websocket'],
secure: true,
'force new connection' : false,
'reconnect' : true,
});
It works, but everytime I change or refresh page, websocket connection disconnect and reconnect (obviusly). My app is not "one-page-app".
There is a way for keep connection alive?
There is a way for keep connection alive?
No. Not if you allow the page to change in the browser.
When the browser changes pages, it will close all resources associated with the old page (including webSockets) and then it will initialize and open the new page. You cannot change that.
The only way to keep a webSocket open is to put it in a window that does not change. That would entail either converting to a single page app (that doesn't change pages) or putting the webSocket in a frame or window that doesn't change. You could have the user install a browser extension (which can maintain persistent connections), but I assume that isn't what you're asking about.
Otherwise, you have to just manage things on your server to handle the fact that a page change within your site will close the old webSocket and open a new one.

Basic Node.js examples not working on Windows 7

I installed node.js from http://nodejs.org/#download, v0.6.6. I am using Windows 7 32-bit.
I've been going through various tuts online, and want to experiment while doing so, but I cannot seem to get node.js working. Node will run my .js file, but any request from the browser times out.
Here is a typical Hello World example that does not work:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337);
Pointing my browser at 127.0.0.1:1337 or localhost:1337 does not work. The request from the browser times out. I've also tried listen(1337,'0.0.0.0') and listen(1337,'127.0.0.1').
I know the server is running; if I CTRL+C and stop node, the browser immediately comes back with ERR_CONNECTION_RESET.
I also tried running the code in this gist, which will not work: https://gist.github.com/1339846. I end up with the console output "Listening!" and then nothing else.
Furthermore, I have tried different ports, and my firewall is off via
netsh firewall set opmode mode=disable
I tried with firewall totally disabled, and the service stopped. If I check connections using netstat -noa, I can see node has a bunch of connections opened for the browsers, all in state CLOSE_WAIT. So it looks like connections are happening, but node.js just isn't working.
The callback function that is supposed to be initiated by a request never executes - I sprinkled some console.log statements in various areas, and they all execute except any in the callback.
I uninstalled, re-installed, tried a couple previous builds, restarted my machine...nothing.
Any help is appreciated!
UPDATE: I have just about given up. I've tried everything I can think of, and it ended up being easier to run node.js in an instance of Ubuntu in VirtualBox than grasp at straws.
!!!!!! Same problem happened for me....
Here is a solution which I have yet to find anywhere:
Look in Windows Firewall with Advanced Security and see if Evented I/O for V8 JavaScript is blocked or appears two times.
If so unblock it and delete the duplicated entry. If you install/uninstall/install nodeJs, there will be 2 entries.
Also when node first runs the Window Firewall dialog opens asking if you want to allow node to have firewall access. If you press "No" or just close the window without asking, it will create Evented I/O for V8 JavaScript AND IT WILL BE BLOCKED.
I ran into the same problem and after reading through the documentation, I unexpectedly ran into what I believe is the solution. In my instance I was noticing that the incoming requests WERE being delivered to node, but the response was never having its 'end' event triggered. So altering incoming firewall rules in windows did not seem to be related to the problem.
So, http.createServer takes in a single argument - a function which should include a request and response parameter. The request parameter seemed to be where the problem lay. The request parameter is an instance of http.incomingMessage. This class only had like one event type, but it was itself also an implementation of Stream.Readable, which is where I found the 'end' event that wasn't triggered. Really for no other reason that to just test which was the first event not triggered, I just added a listener for another type of event ('readable'), and only added a console.log line to it which made the whole thing work.
So the code looks simply something like this:
var http = require("http");
http.createServer(function (request, response) {
console.log('request');
request.on('readable', function(){
console.log('request readable');
});
request.on("end", function () {
console.log('request end');
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello HTTP!');
});
}).listen(8080);
The above code works, whereas the earlier version below without a 'readable' event listener does not ever respond:
var http = require("http");
http.createServer(function (request, response) {
console.log('request');
request.on("end", function () {
console.log('request end');
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello HTTP!');
});
}).listen(8080);
I am not sure why this works except for a little clue in the documentation which reads:
In some cases, listening for a 'readable' event will cause some data
to be read into the internal buffer from the underlying system, if it
hadn't already.
I just tried it and it works for me. Make sure you are not blocking node with your firewall.
I am using Windows 7 32-bit.
What edition of Windows 7 are you using? Eg. Home Premium, Professional, Ultimate?
A thread on the npm github project mentions similar symptoms while installing nodejs modules using npm, and comments seem to narrow it down to being caused by Windows 7 Professional. It being 32/64-bit doesn't seem to matter.
I am having both the problem you describe, as well as the npm installation problem, and am running on Windows 7 Professional 64-bit.
Using XPMode (a workaround mentioned in the npm thread) has allowed me to workaround both of these issues. Although, I suppose this is just a more Windows-y version of your use of Ubuntu in VirtualBox.
Other workarounds tried without success:
Make/run a Debug build of v0.6.6
Make/run a Debug build of v0.6.5 (actually crashed in startup)
Set various Compatability Modes on the installed node.exe
Prepackaged Windows installer of v0.6.5
Go to "Control Panel\All Control Panel Items\Windows Firewall\Allowed
Programs"
Click Allow Programs
select nodejs from the list.
This fixed all the problems for me
I was having the same problem with this code (Http Server example from this link: http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/)
var http = require("http");
http.createServer(function (request, response) {
request.on("end", function () {
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello HTTP!');
});
}).listen(8080);
I tried windows 7 64-bit version, windows XP virtual machine, ubuntu virtual machine ... nothing! It only worked after I commented the "request.on" line. Your example (which doesn't have this line) worked fine for me. I'm using the latest stable build from node.js (v0.10.18 for windows or linux). Hope this helps anyone having trouble with this.

Socket.IO disconnection problem before closing window

I am trying to prevent the client from disconnecting from the server. So before the user closes the window on which the app is open, I do:
$(window).bind("beforeunload", function() {
return("Close the app?");
});
But the problem is that no matter if the user chooses to leave or stay on the page where the app is open, the client get's disconnected (stops listening) from the server, before even I chose an option. So if the user chooses to stay on the page, nothing will be sent or received from the server.
Why can this be? How can this be prevented?
I had exactly the same problem in my project.
When you call socket.connect(), you should set sync disconnect on unload parameter of your connection to false (it is true by default):
var conn_options = {
'sync disconnect on unload':false
};
socket = io.connect(url, conn_options);
You can find more connection options here: https://github.com/LearnBoost/socket.io/wiki/Configuring-Socket.IO
P.S. Hope it's still actual for you :)
UPD.
Since the doc was changed, false is now the default value of sync disconnect on unload
You might not be able to avoid the problem as there are no other events triggering before "beforeunload" at window close that i know of. However,you could work around it by asking the socket to reconnect in the callback of the window close dialog when the user chooses to not exit the page. Reconnecting is pretty easy, just:
socket.connect()
Here's another question that describes reconnecting in more detail:
How to reconnect as soon as disconnect happens

Resources