AS3 LocalConnection Errors - actionscript-3

Not sure where I'm going wrong, for now just trying this out locally. Thanks.
sendingLC.swf does return, LocalConnection.send() succeeded
This is the errors I get from Flash.
Error #2044: Unhandled AsyncErrorEvent:. text=Error #2095: flash.net.LocalConnection was unable to invoke callback myMethod. error=ReferenceError: Error #1069: Property myMethod not found on flash.net.LocalConnection and there is no default value.
Code for sendingLC.swf:
import flash.net.LocalConnection
var sendingLC:LocalConnection;
sendingLC = new LocalConnection();
sendingLC.allowDomain('*');
Security.allowDomain("*");
sendBtn.addEventListener(MouseEvent.CLICK, sendIt);
function sendIt(eventObj:MouseEvent):void {
sendingLC.send('myConnection', 'myMethod');
}
sendingLC.addEventListener(StatusEvent.STATUS, statusHandler);
function statusHandler (event:StatusEvent):void
{
switch (event.level)
{
case "status" :
textArea.text = ("LocalConnection.send() succeeded");
break;
case "error" :
textArea.text = ("LocalConnection.send() failed");
break;
}
}
Code for receivingLC.swf:
import flash.net.LocalConnection
var receivingLC:LocalConnection;
receivingLC = new LocalConnection();
receivingLC.allowDomain('*');
Security.allowDomain("*");
receivingLC.connect('myConnection');
function myMethod():void {trace('Hello World')}

I also had issues with the LocalConnection giving me callback errors, but it stopped when I added the client property to the connection. Then it started working, even in flash IDE.
var conn:LocalConnection;
conn = new LocalConnection();
conn.allowDomain('*');
conn.client = this;
conn.connect('localThingieConnector');

There could be an issue with making the connection in the receiver.
try {
var receivingLC:LocalConnection;
receivingLC = new LocalConnection();
receivingLC.allowDomain('*');
Security.allowDomain("*"); // not sure this line is needed
receivingLC.connect('myConnection');
} catch (error:ArgumentError) {
trace('failure to make connection ' + error.toString() );
}
Also something to note do not test LocalConnections in the flash api do it through a browser when you are first making these as permission issues can be a cranky woman.

Perhaps try making myMethod public like so:
public function myMethod():void{
trace("hello world");
}
Also you should try/catch the send call so you get more information about errors like so:
try{
sendingLC.send('myConnection', 'myMethod');
}
catch(e:Error){
trace(e.toString());
}

Related

ws how to catch : WebSocket connection to 'ws:// failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

i have simple web sockets html5 , when the server is up every thing is working fine
the problem is when i close the server ( for testing )
im getting :
WebSocket connection to 'ws://127.0.0.1:7777/api' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
which i unable to catch its never jumps to onerror or onclose in case of this error
init: function () {
this.m_wsiSendBinary = new WebSocket("ws://127.0.0.1:7681/wsapi");
this.m_wsiSendBinary.onopen = function(evt) {
cc.log("Send Binary WS was opened.");
};
this.m_wsiSendBinary.onmessage = (function(evt) {
this.handleServerResponse(yStr);
this.m_wsiSendBinary.onerror = function(evt) {
};
this.m_wsiSendBinary.onclose = function(evt) {
cc.log("m_wsiSendBinary websocket instance closed.");
self.m_wsiSendBinary = null;
};
}).bind(this);
I do not have full answer, however I dealt with similar issue and have a partial and not so elegant solution (but may help someone). Unfortunately without the elimination of the error message.
Two business requirements:
BR1 - Handle state in initialization when the server is not available.
BR2 - Handle state when the server stops.
Solution for BR1
var global_connection_openned=null;//Here you have the result
init: function () {
global_connection_openned=false;
this.m_wsiSendBinary = new WebSocket("ws://127.0.0.1:7681/wsapi");
this.m_wsiSendBinary.onopen = function(evt)
{
global_connection_openned=true;
};
Solution for BR2 (assumes the BR1)
//somewhere in your project called by setInterval(..) which will detect the connection is lost (and tries to reestablish/reopen the connetion.
{
if (this.m_wsiSendBinary==null || this.m_wsiSendBinary.readyState==3)
this.init();
if (!global_connection_openned)
this.m_wsiSendBinary=null;
}
Anyway, I would be really curious if there is solid and proper solution of this use case.

URLLoader Throwing Uncatcheable ioError when No Internet Connection

Flash is throwing an uncatchable exception when using a URLLoader with no internet connection:
Error #2044: Unhandled ioError:. text=Error #2032: Stream Error
Since I'm developing a phone app, there's always a chance the internet will drop. I want to detect this and show an error dialog. Is there anyway to catch and suppress this error? Code follows:
try
{
var request:URLRequest = new URLRequest(API_URL + "/" + API_VERSION + "/" + gameKey + "/" + type);
request.data = jsonString;
request.method = URLRequestMethod.POST;
request.requestHeaders.push(new URLRequestHeader("Authorization", MD5.hash(jsonString + secretKey)));
var loader:URLLoader = new URLLoader();
loader.data = type;
loader.addEventListener(Event.COMPLETE, onRequestComplete);
loader.addEventListener(IOErrorEvent.IO_ERROR, onRequestError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onRequestSecurityError);
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onRequestStatus);
loader.load(request);
} catch (Error) { trace("URLLoader Failed");}
The exception stack claims the it is raised on the line where the URLLoader is allocated, but while debugging execution runs past that line, and the exception comes from an unknown place. The catch block is never invoked. The error event handlers are hit, but only AFTER the exception is shown as being un-handled by the Flash Player.
Any help would be appreciated. I'm tearing my hair out and can't find the answer online (other people have reported the same problem but there are no solutions.)
Flash is throwing an uncatchable exception when using a URLLoader with no internet connection
To catch them, go with uncaughtErrorEvents in LoaderInfo. For example you could subscribe for the uncaught errors and manage them with some fallback logic:
//Somewhere, you could manage it globally, or declare before risky part
loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, onUncaughtError);
private function onUncaughtError(e:UncaughtErrorEvent):void {
e.preventDefault();
trace("Scorpion: come here! - " + e.toString());
}

Should I call close() on URLLoader after an error?

When using URLLoader two types of errors are possible: exceptions which can be catched in try {} block and error events which can be handled by handler functions.
Should I call close() on my URLLoader object after exception/error event occurs?
Interesting question - I gave this code a try and didn't get the error you would expect (stream error):
var urlLoader:URLLoader = new URLLoader();
urlLoader.load( new URLRequest("http://stackoverflow.com/test.jpg") );
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, error);
function error(e:IOErrorEvent):void
{
// Don't get the stream error, meaning the stream is still open.
urlLoader.close();
}
I then thought to myself that maybe it just closes half a second later, so I attached a setTimeout() to the close call. Still didn't get the error.
function error(e:IOErrorEvent):void
{
setTimeout(function()
{
// Still no error.
trace("Test.");
urlLoader.close();
}, 3000);
}
To double check, I ran this to make sure we still actually get that error:
var urlLoader:URLLoader = new URLLoader();
urlLoader.close(); // Error: Error #2029: This URLStream object does not have
// a stream opened.
So, it seems as though you actually do need to .close() a stream if there is an error. How weird. That said, I am still in disbelief, so I welcome any evidence against this.

Code error in NetConnection.call method

I am new to ActionScript 3. I am attempting to call the server from the client using the nc.call() method to see if this was a good option to use for clients to communicate back and forth in a chat application.
I received a compile error message:
1118: Implicit coercion of a value with static type Object to a possibly unrelated type flash.net:Responder.
Can somebody please help me fix this error?
This is my client-side code below:
import flash.net.NetConnection;
import flash.events.NetStatusEvent;
var nc:NetConnection = new NetConnection();
nc.connect("rtmfp:/fms/textchatexample");
nc.addEventListener(NetStatusEvent.NET_STATUS, netHandler);
function netHandler(event:NetStatusEvent):void {
switch(event.info.code) {
case "NetConnection.Connect.Success":
trace("Your Connected UP");
break;
}
}
var test:Object = new Object();
test.onResult = function(arg) {
trace(arg);
};
nc.call("sendMsg", test, "just, a test call"); ERROR LINE
try to replace your Object instance with a Responder:
var test:Responder = new Responder(
function(result):void
{
trace('ok :', result);
},
function(status):void
{
trace('status :', status);
});
instead of your Object

How to pass errors conditions

In web app development I would like a consistent way to catch and report error conditions. For example, a database update routine may detect a variety of error conditions and ideally I would like the application to capture them and report gracefully. The code below din't work because retdiag is undefined when error is thrown...
function saveData(app,e) {
var db ;
var retdiag = "";
var lock = LockService.getPublicLock();
lock.waitLock(30000);
try {
// e.parameters has all the data fields from form
// re obtain the data to be updated
db = databaseLib.getDb();
var result = db.query({table: 'serviceUser',"idx":e.parameter.id});
if (result.getSize() !== 1) {
throw ("DB error - service user " + e.parameter.id);
}
//should be one & only one
retdiag = 'Save Data Finished Ok';
}
catch (ex) {
retdiag= ex.message // undefined!
}
finally {
lock.releaseLock();
return retdiag;
}
}
Is there a good or best practice for this is GAS?
To have a full error object, with message and stacktrace you have to build one, and not just throw a string. e.g. throw new Error("DB error ...");
Now, a more "consistent" way I usually implement is to wrap all my client-side calls into a function that will treat any errors for me. e.g.
function wrapper_(f,args) {
try {
return f.apply(this,args);
} catch(err) {
;//log error here or send an email to yourself, etc
throw err.message || err; //re-throw the message, so the client-side knows an error happend
}
}
//real client side called functions get wrapped like this (just examples)
function fileSelected(file,type) { return wrapper_(fileSelected_,[file,type]); }
function loadSettings(id) { return wrapper_(loadSettings_,[id]); }
function fileSelected_(file,type) {
; //do your thing
}
function loadSettings_(id) {
; //just examples
throw new Error("DB error ...");
}