This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Managing a Connection
|
85
which is notified whenever the connection status changes. When a connection is first
established, the objects and components that rely on it can begin using it. When a
connection is closed, these objects may have to be disabled or disposed of. It is espe-
cially important that the user doesn’t experience a sudden and unexplained loss of
functionality when a network connection is dropped by the server or lost because of
a network problem.
For the most part, when a connection is closed, the
info object passed to the onSta-
tus( ) method will have a
level value of “status” and a code value of “NetConnection.
Connect.Closed”. This will happen if the network goes down, the server disconnects
the client, the server stops, or the connection is closed using NetConnection.close( ).
It is also possible that the
level value will be “error” and the code value “NetConnec-
tion.Connect.AppShutdown”. The following sections discuss how to deal with vari-
ous connection status changes.
Dealing with Success
When Flash establishes a connection, any streams and shared objects that rely on the
connection can be set up. Testing for the “NetConnection.Connect.Success” code in
the onStatus( ) handler is the easiest way to do this:
if (info.code = "NetConnection.Connect.Success") {
// Initialize and connect dependent objects and components (not shown).
}
Avoiding Timing Problems
A common—and sometimes difficult to debug—problem occurs when scripts define
the onStatus( ) handler after calling the connect( ) method:
nc = new NetConnection( );
nc.connect( ); // WRONG: do this after onStatus is defined!
nc.onStatus = function (info) {
trace("info.code: " + info.code);
};
If connect( ) is called prematurely, the network connection may be established or the
connection rejected before the onStatus( ) handler has been defined. The result is that
the messages representing those events are never returned to the handler. The onSta-
tus( ) method must always be defined before the connect( ) call is made. The preceding
example should be rewritten as:
nc = new NetConnection( );
nc.onStatus = function (info) {
trace("info.code: " + info.code);
};
nc.connect( );

Get Programming Flash Communication Server now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.