How does WebSockets exactly work? Implementing them seemed weird.
First you construct the object with the address, then you define the callbacks like onopen which is called when the connection is opened. Now how does that happen if I told the websocket to connect while constructing it? If the constructor connects in async way, is it guaranteed that my onopen will be called.
To sum it up:
1) When does the websocket decide to connect, when I declare all callbacks?
2) Is send() method async? If so, is there a way to call it sync?
EDIT: I have found out send() is async, there is a bufferedAmount attribute that returns the amount of data that is buffered to be sent. However, the second part of the second question still stands.
I've found a good way to explain how this part of an event loop works is this:
In an event loop, everything runs asynchronously, except for your code.
Consecutive statements will always be executed before the next event loop iteration happens. This means that you can safely assign event listeners to the ws object, because you know that it cannot call them before current iteration completes.
As for sending, as you noticed correctly, those values are generally buffered. However, it's probably a bad idea to send any messages before the onopen event is fired, as you're buffering messages on a not yet opened connection.
I hope this answers your question.
Related
I was creating a script and i want to know how do i make the game wait until a funcion is called
If someone awnser me,ill be thankful
Firstly do not use loops, use events!
To wait for an event to happen you can use the wait method, like so:
print("Starting to wait for touch")
workspace.Part.Touched:Wait()
print("Touched!")
This will wait for the part to be touched before it continues the script.
But ofcourse, other scripts will still run, the game is not "paused", it is just that script's execution that is suspended until the event is fired.
You can also make custom "wait for call" by using for example a BoolValue like so:
local WaitObject = Instance.new("BoolValue")
function WaitOn()
WaitObject.Changed:Wait()
end
function StopWait()
WaitObject.Value = not WaitObject.Value
end
You can also place the BoolValue in the game and do the wait and stop wait in separated scripts.
If you do it in same script, remember to use different threads
I have a simple accessor in my class:
public function get loggedIn():Boolean
{
var loggedIn:Boolean = somePrivateMethodToCheckStatus();
return loggedIn;
}
The API I'm now working with checks login status in an asynchronous fashion:
API_Class.addEventListener(API_Class.LOGIN_STATUS,onStatusCheck);
API_Class.checkLoginStatus();
function onStatusCheck(evt:API_Event):void
{
//evt.loggedIn == true or false
}
Is there a way I can perform this asynchronous request without exiting my accessor?
Simple answer: No, there is not. You will have to set up login verification in an asynchronous fashion.
I am a bit curious: Why is there a need to repeatedly poll the login status remotely? If your user logged in from within the Flash application, the status should be known. Same goes for logging out. If login and logout is handled from outside the Flash app, why not implement a notification mechanism (via JavaScript or socket connection)?
Also, if not being logged in prevents users from performing actions on the server, you could check for authorization on the server, whenever remote calls are made, and return an error if the session has expired. This would still be more efficient than repeatedly polling status info.
Not really, no. Flash runs in a single thread, and every function has to finish before events etc will be called.
One (sort of) solution would be to return three values; "yes", "no" and "pending". If it's pending the loggedIn()-method would start a check, and the client of that method should check again in a little while.
Another way would be to have the loggedIn-method send the answer to a callback instead. Eg "getLoggedInStatus(callback:Function)"
You may be interested in http://www.as3commons.org/as3-commons-eventbus/index.html
It is a handy lib that focuses on asynchronous jobs.
Alright dudes... I have a problem that is looking for an answer more specific than the seemingly obvious solution.
I have a block of code that I want to execute directly after a url is known to be valid. What I mean by 'valid' is that the program has checked to see if that filepath actually exists. This could be accomplished by a COMPLETE listener, because after all, a loader couldn't finish loading its content if the referenced file didn't exist, but I want it to happen before any of the bytes begin to get sucked in. I have also tried the HTTPS_STATUS event, with a conditional saying "if the status is this [some non-error status number], then run this block of code." This would have worked great, except that different environments produce different network codes, and some even can't distinguish between errors and non-errors, just returning 0's no matter what. Because of this, I can't write a conditional that works no matter what browser....
So, anyone got any ideas?!?!?!?!
If this doesn't work post your code.
myUrlLoader.addEventListener(Event.OPEN, openHandler);
//Dispatched when the download operation commences following a call to the URLLoader.load() method.
I want to create some kind of AJAX script or call that continuously will check a MySQL database if any new messages has arrived. When there is a new message in the database, the AJAX script should invoke a kind of alert box or message box.
I’m not quite a AJAX expert (yet anyway) and have Googled around to find a solution but I’m having a hard time to figure out where to begin. I imagine that it is kind of the same method that an AJAX chat is using to see if any new chat-message has been send.
I’ve also tried to search for AJAX (httpxmlrequest) call in a continuously and infinity loop but still haven’t got a solution yet.
I hope there is someone, which can help me with such a AJAX script or maybe nudge me in the right direction.
Thanks
Sincerely
Mestika
Step 1 - You need a server-side page that you can call that checks to see if something new has arrived.
Step 2 - You could adapt the sequential AJAX request script from here (it uses jQuery to simplify the AJAX requests):
http://www.stevefenton.co.uk/Content/Blog/Date/201004/Blog/AJAX-and-Race-Conditions/
Currently, this script is for queuing a list of sequential AJAX requests, but you could use it to continually check by changing it like this...
var InfiniteAjaxRequest = function (uri) {
$.ajax({
url: uri,
success: function(data) {
// do something with "data"
if (data.length > 0) {
alert(data);// Do something sensible with it!
}
InfiniteAjaxRequest (uri);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
};
InfiniteAjaxRequest ("CheckForUpdate.php");
What are the benefits of using this script?
Well, rather than checking every "x" seconds, it will only check once the previous request has been received, so it chains the requests. You could add in a delay to throttle this constant request, which I would highly recommend you do - otherwise you will be hitting your site with way too much traffic. You would add that delay in AFTER you've done something with the response, but BEFORE you call back into "InfiniteAjaxRequest".
Here's your nudge:
Get one of the available JavaScript frameworks (jQuery seems to be the most common, but there are others)
flip though the documentation on the AJAX methods it provides, choose a method for your task that seems appropriate
build a request to your site that fetches the info and reacts on the response (shows a message box or updates some part of your page), wrap that in a function
make sure request errors do not go unnoticed by implementing an error handler
check out setInterval() to call that function you've just made repeatedly
final step: make sure that the interval will be stopped in case of an error condition (or provide a on/off button for the user, even) so the server is not hammered needlessly
There is a technique called Comet where-by your client-side script would instantiate a HTTP request which remains open for a long time. The server can then push data into the response as they happen. It's a technique to deliver a push notification.
The Wikipedia link has more information on real-world implementations.
Instead of polling the server with AJAX calls you could also use push technology (COMET).
This way you can push the results to the client(s) as soon as the server is done with it's work.
There are many frameworks available like:
JQuery plugin
Cometd
Atmosphere (if your on java)
I am creating a javascript API for SCORM 2004 4th Edition. For those who don't know about SCORM, basically it is an API standard that eLearning courses can use to communicate with an LMS (Learning Management System). Now the API has to have the following method:
Initialize(args)
GetValue(key)
SetValue(key, value)
Terminate(args)
Commit(args)
GetDiagnostic(args)
GetErrorString(args)
GetLastError()
Now Initialize has to be called before anything else, and Terminate must the last. GetValue/SetValue can be called anywhere in between there. What I am doing is in the Initialize method I am getting some JSON from a web service and storing that in the API (to be used when using the GetValue/SetValue methods later). The problem I am coming across is that the AJAX call via jQuery is asynchronous, so the Initialize method call could be done before the JSON is loaded. With that being the way it is, a call to GetValue after calling Initialize could cause unexpected issues b/c the JSON that GetValue uses isn't there yet. My question is this: What can I do to ensure that the JSON is loaded before the GetValue/SetValue methods are called? I know the simple answer is to make it synchronous, but that is not advised mostly, and it doesn't seem to want to do that for me. Here is my code regarding that:
function GetJSON(){
var success = false;
$.ajaxSetup({async:false}); //should make it synchronous
$.getJSON("http://www.mydomain.com/webservices/scorm.asmx/SCORMInitialize?
learnerID=34&jsoncallback=?",
function(data){
bind(data);
success = true;
}
);
return success;
}
function bind(data){
this.cmi = eval("(" + data.d + ")");
$.ajaxSetup({async:true}); //should make it asynchronous again
}
Does anyone have any ideas? I would really appreciate it!
You've articulated the problem well. After the SCO calls Initialize, the CMI data needs to be immediately available for the SCO to make subsequent GetValue calls. However, making synchronous AJAX calls isn't advised, if there is a hangup in the request, it can lock up the entire browser until the request returns or times out. The solution is to pre-load all of the required data before the SCO is loaded. In our SCORM Engine implementation, we preload all of the data (CMI and sequencing) when the player is launched and then use a background process to periodically commit dirty data as the learner progresses through the course. It can get a bit tricky to ensure that all data is properly persisted when dealing with the combinations of possible window launching and exit scenarios, but it's certainly possible. You will want to avoid any requests to the server from within a SCORM API call as SCOs will often flood the LMS with big batches of calls. Making server requests within those calls can seriously degrade the learner's experience and place a performance burden on the server.
Mike
The way we approached this problem was to queue the CMI data in the API when the SCO is launched. We first navigate to a launch page that loads the CMI data into the API's queue, and then the laucnch page actually launches the SCO. When the SCO calls intialize, we just move the data into the CMI.