Is there anyway in flex to get the status of server? - javascript

we have an application where button click in flex side restarts the server and makes the client logged out. once after logout, If user logs in it gives error since the server is not up by the time. In our scenario the server takes time to restart because of the stuff(like back up). I want the user to be notified of the webserver status if he tries to log in.
is there any way to monitor the status of server in Flex side. or Will javascript help in finding whether the server is up or not?.
Also I tried redirecting to html page using external interface but I am not sure how to automatically redirect it again to the swf file when the server becomes active.the server downtime is not known(may be 2 or 5 or 10 minutes.)
So what would be the best approach.Any help would be of greatly appreciated.

Using URLLoader you can try to download a file on the server and listen to ioError or httpStatus.
private var testLoader:URLLoader;
private var testRequest:URLRequest;
...
testRequest = new URLRequest("http://server/testFile");
testLoader = new URLLoader(request);
testLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
private function onStatus(HTTPStatusEvent:event):void
{
//test the status, if the server is up, reconnect, else...
testLoader.load(testRequest);
}

Interesting problem. When you mean restart, do you mean just a specific service like Apache or like an actual reboot of the server? I ask because it would mean different scenarios. I'm not exactly sure what you're doing, but I'll assume that you're rebooting the server.
One of the problems here is that the client logs out, which is something we do not want. What I would do is have a second server which it's sole purpose would be authentication and giving status on the other server. This is a 'man in the middle' approach where this server doesn't log you out, but all calls are redirected to the other server.
From the Flex side, you can have it calls the 'man in the middle' to see what's the status. Depending on the technology you're using (polling vs pushing), you can get the data needed and show the user the status.

Related

How detect changes of an api

I have a api that returns if the building is open and how much peapole are in there.
Now i want my Discord Bot to send a message when the Building opens.
How do i do that?
if the api recives a request the response is looks this :
state: {
open: false/true
}
It may be helpful to clear out the terminology: the "API" in this context is the endpoints exposed by the server and their request/response schemas (you can think of it as the fields you send and receive back). Now, this doesn't change in your case: it's the same endpoint, and the same fields. What changes is the value.
Now, you are probably doing a HTTP request to a given URL, where the server is. And in HTTP world, we say that we are requesting a resource. The resource behind https://stackoverflow.com is the homepage of this website. The resource behind the endpoint you are calling is a building's state. This resource changes overtime, it may open or closed at any time, people going in and out. But the API doesn't change in this case.
Let's reword your question, so it can be clearer: How can a client know when a HTTP resource changes? If your server only exposes this endpoint to know the state of the building, the answer is a sad "it can't". Let's say that I close the building, the server knows it somehow and now the building's state is {"open": false}. But the server doesn't have any mechanism to say to your client that the state changed, the server just waits for the client to ask what the state is, and returns. Allowing a server to send data to your client without the client requesting first adds some complexity to your architecture, and although there's a bonus (the client will know of state changes as soon as possible), in your case, it may not be necessary.
One alternative is long polling, in long polling your client makes a request to the server and the server doesn't respond immediately, it... waits. Waits for an update, like a change in building's state. When an update happens, then it sends a response. The client, in turn, requests again! And waits for the server to send an update... In practice, the client will keep up with the server state. The mentioned article for long polling gives a good example: https://javascript.info/long-polling#regular-polling
The one caveat is that the server must also support long polling. If the server just returns whatever the resource's state is, then the client will keep receiving the same state over and over. Another valid solution is instead of waiting for updates, the client keeps requesting the server for every few seconds. You may miss some updates! But in some cases, it's fine to lose track of a few updates.
Ok, enough theory. What about your case? If you want to know if a door is open or closed, but don't care to know when it happens, you can just request the server every five seconds or so:
In some pseudo javascript code, and very inspired by the long polling article mentioned before:
async function subscribe() {
let buildingState = null
while (true) {
const response = await fetch("/subscribe")
if (response.status != 200) {
// An error - let's show it
showMessage(response.statusText)
}
// Get and show the message
const message = await response.json()
// a function that returns true/false if the state is different
if (stateChanged(message, buildingState)) {
updateDiscordBot(message)
buildingState = message
}
// wait five seconds and repeat
await new Promise(resolve => setTimeout(resolve, 5000));
}
}
subscribe();
This works fine. But if you want for your client to immediately know when a door is opened or closed, this is not enough: opening and closing a door is a quite fast action, and even if you request the server every second, you may lose updates. In this case, the server needs to change. Either by implementing long polling, or something like websockets... you didn't mention that the server is in your control, but if it doesn't, it may be helpful to talk with who maintains it to work out a solution.
If you only have pull access to that API then the only way to detect state change is to periodically send a request, store response, and trigger your bot on stored response change.

Determine Signal R connection status without broadcasting Clients.All.someMethod() and blowing up client side resources

I'm concerned about using Clients.All in my C# Signal R hub class
Clients.All.setConnectionStatus(profileId, true);
I'm calling it in both OnConnected() and OnDisconnected(bool stopCalled)
to show the online status of my logged in users.
OnDisconnected() isn't as bad because it's only being called when someone actually logs off
ex.
public override Task OnConnected()
{
string profileId = Context.User.Identity.Name;
_connections.Add(profileId, Context.ConnectionId);
Clients.All.setConnectionStatus(profileId, true);
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
string profileId = Context.User.Identity.Name;
_connections.Remove(profileId, Context.ConnectionId);
if (stopCalled == false) // log off only
Clients.All.setConnectionStatus(profileId, false);
return base.OnDisconnected(stopCalled);
}
My concern -> Blowing up the users machine client side with javascript code constantly running in the browser!
Scenario -> If I have > ~1000 users online and logged in traversing to different pages, I will be broadcasting to all of them a signal R connection Clients.All.setConnectionStatus(profileId, true);
which in the javascript hub looks like this below which could easily end up blowing up the users browser, because it would be constantly receiving these broadcasting connection status calls!!!
scope.chat = $.connection.chatHub;
// Receive and set the connection status
scope.chat.client.setConnectionStatus = function(profileId, isConnected) {
// look for prfileId in html
var $profileStatusElement = $(".online-status-profile[data-id='" + profileId + "']");
var $profileChatElement = $(".online-status-chat[data-id='" + profileId + "']");
if (isConnected === true) {
// change the online status
} else {
// change the online status
}
};
I have chat windows to users (online) like below that shows a users status next to their name. So I know if the person I'm sending a message to is online or not!
When I first load the chatbox, I fetch the online status server side, but after that it's up to the OnConnected() and OnDisconnected() methods in my hub to set the online status of the person I'm chatting with.
There's got to be a better way then broadcasting the signal out to 'all' online users on my site? But the only way I can think of is to poll the status every so often on some javascript timer, but I hate that idea!!
Another way would be to keep some kind of in-memory collection of who each person is chatting with, but that seems like it could get really messy and could end up up not being very accurate, being there could be so many things in between the client and server that could cause a disruption to mismanage the in-memory collection of who's connected to whom! Any thoughts or ideas here would be greatly appreciated!!
FYI -> I also have a messages page, that shows a list of all the recent conversations I've had with users like below. And on this page I show the online status of these users as well. On this page I fetch the online status of each user on the server before I render the page, same as the chat box, but once the page is loaded, it's up to the OnConnected() and OnDisconnected(bool stopCalled) to set the online status of each user on the page.
You're doing in right way with signalR. I guide you based on your concerns/scenarios:
My concern -> Blowing up the users machine client side with javascript
code constantly running in the browser!
Don't forget that you are using a browser underlying functionality (WebSocket), so we have no choice unless running some js code inside client loaded page. You take advantage of browser capabilities here.
Scenario -> If I have > ~1000 users online and logged in traversing to
different pages, I will be broadcasting to all of them a signal R
connection Clients.All.setConnectionStatus(profileId, true);
Before proposing any solution, I exhort you to employ grouping logic in your application. Grouping reduces the volume of synchronizations.
If you working on a public chat room (which can contain large number of people), by employing server side strategies simply you'll make your code to a dirty one! Yes, Any user who navigates or refreshes the page can cause a redundant update to all the clients. Best Solution is turning you page to SPA (working with API call or Ajax call) with no page refresh. I believe that any real-time web application should take advantage of modern web technologies. This will solve almost every problem which you suffer (e.g no page refresh, no reRun, no disCoennection & etc ...).
Solutions like using a js timer to fetch latest status for users is not clean or desirable.

Cordova Android- Keep sending AJAX request to the server while the device is in background mode

I need to keep performing Ajax request to the server even if the device is in background, I’ve tried the “cordova-plugin-background-mode “ https://github.com/katzer/cordova-plugin-background-mode ,
Please see the code below ,but for some reason it doesn’t work
Any help would be appreciated to solve this problem
cordova.plugins.backgroundMode.on('activate', function (){
window.setInterval(function () {
//Ajax request every 6 S
}, 6000)
});
It stops sending the Ajax request when the device is in background mode; I need this to check if the user still logged in his/here account
Basically you want your app to consider your users as online as long as they have started the app and keep their phones on? If this is true, then you can simply assume they will stay online forever.
When your app is sent to the background, you must do what any other app does: Consider the user is no longer online. Do not waste user resources and network data from their carrier just to see if the user's phone is still on, this makes no sense at all.
Whenever the app is active and running, you update your database on every request, or every few minutes with a timer if there's no user-initiated network activity.

Node.js error handling with socket.emit

I have some node.js client side code like this:
socket.emit('clickAccept', { myrecid: recid });
Server side node.js code gets it fine and all is well.
If I take the server down to simulate a server side outage, then click the button that fires this socket.emit on the client side, this happens:
Nothing really, I guess it might eventually time out
When I bring the server back up, the clicks end up being sent to the server and the server acts on them (TCP-like I Guess).
What I want to happen is for those socket.emit calls to die after a short timeout and not send when the server comes back up, it causes all sorts of confusion because if they click 3 times, nothing happens, then when/if the connection or server comes back up they get 3 reactions all at once.
Also, if they click and it times out because the server is down, I would like to show an error to the client user to let them know that basically the click didn't work and to try again.
I know how to act on and show an error if the socket goes down but I don't want to do this if they aren't trying to click something at that time. No sense is firing errors at the user because the socket went down briefly if they have no need to do anything at that moment.
So, to be clear, I only want to show an error if they click on the button and the socket between the client and server is down. AND... If they get an error, I want to kill that emit, not save it all up and fire it and all the other clicks when the server comes back up a few seconds later.
Thanks in advance and I hope that was at least reasonably clear.
The root of your issue is that socket.io attempts to buffer any data that it can't currently send to the server (because the connection to the server is disconnected) and when the server comes back up and the connection is restored, it then sends that data.
You can see the technical details for how this works here: socket.io stop re-emitting event after x seconds/first failed attempt to get a response
You have several implementation options:
If socket.io already knows the client is not connected to the server, then don't buffer the data (perhaps even give you back an error to show to your user).
When socket.io reconnects and there was data buffered while the connection was down, clear that data and throw it away so old data isn't sent on a reconnect.
Implement a timeout to do one of the above after some sort of timeout.
So, to be clear, I only want to show an error if they click on the button and the socket between the client and server is down. AND... If they get an error, I want to kill that emit, not save it all up and fire it and all the other clicks when the server comes back up a few seconds later.
Probably, the simplest way to do that is to implement a version of what is shown in the above referenced answer:
Socket.prototype.emitWhenConnected = function(msg, data) {
if (this.connected) {
this.emit(msg, data);
return null;
} else {
return new Error("not connected");
}
}
Then, switch your code from using .emit() to use .emitWhenConnected() and check the return value when using it. If the return value is null, then no error was detected. If the return value is not null, then there was an error.
Thanks for the other answers and help. I ended up solving this in a super simple way. See below:
if (socket.connected){
// Do your thing here
} else {
// Throw error here that tells the user they're internet is likely down
}
Hope this helps someone out there, it was a huge improvement in our code to make sure that user's are getting proper feedback when if they have brief network/internet outages.

atmosphere-javascript long-polling not "refreshing" every minute

Hi I'm new user to atmosphere, and set up a simple test that worked fine. We used long-polling, and the behavior was that my client would send the server a GET that would stay open until:
data was returned by the server
a minute elapsed
in both cases, the client would immediately send another GET for the server to hold open. Most of the time no data was sent, so every minute the GET would be "refreshed." I assumed this was the default behavior because maybe certain browsers or networks would shut off a GET that exceeded a certain time limit, so this was a way to avoid that.
Question:
Is this refresh controlled by the client or the browser? I poked around and couldn't figure out if the client was closing the connection on its own and sending a new request, or if it was the server.
The reason I ask is that the server got deployed, and now that refresh is no longer occurring. My client GET now stays open to the full 5 minute (default) timeout and then throws the timeout event, then reconnects for another 5 minutes.
Server team claims "nothing changed," ha-ha. So did I do something or what? Please let me know! Thank you!
request object:
var request = {
url: 'xyz',
transport: 'long-polling',
reconnectInterval: 5000,
maxReconnectOnClose: 20,
enableXDR: true
};
Edit: the atmosphere server was changed from 2.1.3 (working) to 2.0.7 (not working) when the deploy occurred. When changed back, the 1 minute refresh behavior re-appeared. The problem is that 2.1.3 is not compatible with the server they are using, thus the down-grade.
Question: what is this feature called, is this the heartbeat or something else? Can someone tell me what change was made that would cause this. I've looked through the release notes and nothing jumped out at me.

Categories

Resources