Node.js how to keep connection between page loads - javascript

On my website I have a list of all online users, updated in real-time by node.js (I'm using now.js)
The problem is, when a user navigates my site, they of course disconnect for a couple of seconds when the new page is loading. Which means they disappear from the list for all other clients, to pop back in just seconds later.
Is there any way to set a timeout on the disconnect function, e.g. if user has not reconnected in 30 seconds, remove from the list otherwise don't?
Or if there is a better way to accomplish this? Can someone please point me in the right direction :)
EDIT:
Came up with a working solution, if anyone would like to know. On server side I have this function
nowjs.on('disconnect', function() {
everyone.now.clientDisconnected();
});
which whenever a user disconnects calls this function on the client
now.clientDisconnected = function() {
setTimeout(function() { now.serverUpdateUsers(); }, 20000);
}
So instead of updating the users right away, we wait 20 seconds. By then the user should have finished loading the new page, and no difference will show for all other clients.
The serverUpdateUsers(); is the serverside function that gathers all user data and pushes it out to all clients.

I'm not exactly sure if you can modify Socket.IO's settings with now.js (which uses Socket.IO), but if you could (not sure, never used now.js) you should set the heartbeat interval to be bigger:
https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO
heartbeat interval defaults to 20 seconds

Related

How to run asynchronous tasks for multiple users

So I've this project for school who is about "triggers" for social networks.
Let me explain:
- A user can register for our application and login
- He can sign in for multiple services like Facebook, Twitter etc.
- Then their is what we call triggers, once he signed in on our application and registered his services, everytime he will post something on twitter for example my server will see it and post it on Facebook aswell.
I knew nothing about node.js a month ago so I'm kinda new to all this async stuff but I took some course to help myself. So far so good I can now manage users etc, (I've again some research to do with oauth).
My biggest problem is this "real-time" update on our server.
I mean I searched on the internet and saw this what we call polling (?), the idea to make request frequently to a server every X seconds.
So with a bit a sudo code this what I tought it would look like:
For each User
asynchronously watch for every update on Facebook and Twitter for
this User
So I did some research about performing request every each second and found about setInterval and setTimeout
const watchSocialMedia = setInterval(function(){
Users.forEach(user => {
User.watchAndPostAnyNewPost() //
}
}, 60000);
So I put some dummy data to illustrate.
Problem is I don't think It'll be done asynchronously ?
I mean the ideal is if I could put one time for each user a 'watcher' like saying
For each User
User.watchAndPostAnyNewPost()
where watchAndPostAnyNewPost() look like this
class User () {
...
const watchAndPostAnyNewPost = setInterval(function(){
fetchFacebook();
fetchTwitter();
}, 60000);
}
So each user have his own setInterval function running on him to check if he posted anything
Anyone can tell me if it's even possible ? :-)
Thanks a lot for reading me !!!

Refresh DIV by command from server

I want to have a page that uses a mySQL database for its information, let's just say its a 0 or 1
I want the page to auto refresh a div with the value 0 or 1 from the database at a specific interval.
But I would like anyone who is viewing the page to get the same information at the same time. So I would like the server to be in charge of the interval.
How could I do this?
There are several possibilities:
1) Websockets is the latest of the technologies. If you really want near realtime update of the page and have an Infrastructure providing the possibilities, that is the way to go
2) Comet or long polling would be a second alternative
3) The most primitive - but working - startingpoint would be to constantly poll your server. Stackoverflow Article
You can use a JavaScript timer that will check server for any updates and return updated values to the client using Ajax. You can use setTimeout() function as given here:Jquery/Ajax call with timer
A sample you can try
(function worker() {
$.get('ajax/test.html', function(data) {
// Now that we've completed the request schedule the next one.
$('.result').html(data);
setTimeout(worker, 5000);
});
})();

Meteor.jd, realtime latency with complex pusblish/subscribe rules?

I'm playing with realtime whiteboards with meteor. My first attempt was working very well, if you open 2 browsers and draw in one of them, the other one updates in a few milliseconds ( http://pen.meteor.com/stackoverflow )
Now, my second project, is to make an infinite realtime whiteboard. The main thing that changes now, is that all lines are grouped by zones, and the viewer only subscribe to the lines in the visible zones. And now there is a dealy of 5 seconds (!) when you do something in one browser to see it happen in the other one ( http://carve.meteor.com/love ).
I've tried to add indexes in the mongo database for the fields determining the zones.
I've tried updating the Collection only for a full line (and not each time I push a new point like i my first project).
I've tried adding a timeout not to subscribe too often when scrolling or zooming the board.
Nothing changes, always a 5 seconds delay.
I don't have this delay when working locally.
Here is the piece of code responsible for subscribing to the lines you the visible area :
subscribeTimeout=false;
Deps.autorun(function () {
var vT=Session.get("visible_tiles");
var board_key=Session.get("board_key");
if (subscribeTimeout) Meteor.clearTimeout(subscribeTimeout);
subscribeTimeout=Meteor.setTimeout(subscribeLines, 500);
});
function subscribeLines() {
subscribeTimeout=false;
var vT=Session.get("visible_tiles");
console.log("SUBSCRIBE");
Meteor.subscribe("board_lines", Session.get("board_key"),vT.left,vT.right,vT.top,vT.bottom, function() {
console.log("subscribe board_lines "+Session.get("board_key"));
});
}
I've been a SysAdmin for 15 years. Without running the code, it sounds like an imposed limitation of the meteor.com server. They probably put in delays on the resources so everyone gets a fair share. I'd publish to another server like heroku for an easy deploy or manually to another server like linode or my favorite Joyent. Alternatively you could try and contact meteor.com directly and ask them if/how they limit resource usage.
Since the code runs fast/instantly locally, you should see sub-second response times from a good server over a good network.

What is the best way to implement idle time out for web application (auto log off)

I want to implement an idle time-out for the web application that we are building. I had earlier achieved this using AsynchronousSessionAuditor from codeplex, which essentially looks for the formsauthentication and session cookie timeout by constant polling.
But it has a draw back of not respecting the client side events, it will look for only last postback to decide when to log off.
The jquery plug jquery-idle-timeout-plugin from erichynds solves this issue of client side events but suffers from another drawback that is not able to recognise user is active on some other tab.
Is there anyone already fixed the TABBED browsing issue with jquery-idle-timeout-plugin already? Or is there any better approach of application time out for web applications (by the way this web app is build using asp.net f/w)
If I understand your question right, it is not possible, since there are no events triggered in javascript for activity outside of the current window/tab.
Unless you have a addon to go along with your website for each browser, which could monitor all activity in the browser, but that is not really a practical approach.
Well, you'd have to code it by hand, which is not really hard. You can use the onfocus and onblur functions to do something like this:
$(function() {
window.isActive = true;
$(window).focus(function() { this.isActive = true; });
$(window).blur(function() { this.isActive = false; });
showIsActive();
});
function showIsActive()
{
console.log(window.isActive)
window.setTimeout("showIsActive()", 2000);
}
function doWork()
{
if (!window.isActive) { /* Check for idle time */}
}
If you make a little search you can find that varaieties of this question have already been asked and answered, you can probably find a solution you can implement with one of the plugins you mentioned.
Try:
Run setTimeout only when tab is active
or
How to tell if browser/tab is active
EDIT--> ADDED:
Or I'd try a different approach. You could create a cookie with some hash and save that hash in your DB with a timestamp that updates whenever the window is active (you could check every 5 seconds or something, it's not an intensive request)
Then, do another check before(but in the same request) to see how much time has passed since the last timestamp and log them out if necessary.
it won't log them out isntantly when time has passed, but it will when they try to access the site either by opening it again or by focusing on the tab/window.

Handling server-side aborted long-poll/comet updates in jquery

I have an application which uses an open JQuery Ajax connection to do long-polling/comet handling of updates.
Sometimes the browser and the server lose this connection (server crashes, network problems, etc, etc).
I would like the client to detect that the update has crashed and inform the user to refresh the page.
It originally seemed that I had 2 options:
handle the 'error' condition in the JQuery ajax call
handle the 'complete' condition in the JQuery ajax call
On testing, however, it seems that neither of these conditions are triggered when the server aborts the query.
How can I get my client to understand that the server has gone away?
Isn't it possible to add a setInterval() function that runs every few seconds or minutes? That way you can trigger a script that checks whether the server is still up, and if not, reset the comet connection. (I don't know what you use for the long-polling exactly though, so I don't know if it's possible to reset that connection without a page reload. If not, you can still display a message to the user).
So something like this:
var check_server = setInterval(function() {
// run server-check-script...
// if (offline) { // reset }
}, 60000);

Categories

Resources