Table of Contents

XMLSocket.onConnect( ) Event Handler Flash 5

invoked when a connection attempt is completed, successfully or otherwise
socket.onConnect(success)

Arguments

success

A Boolean indicating whether the connection attempt succeeded (true) or failed (false).

Description

The onConnect( ) event handler is executed when a previously invoked connect( ) operation finishes. The execution of onConnect( ) does not necessarily mean a connection has been successfully established�it is executed whenever the connection attempt finishes, whether or not the attempt was successful. The callback handler specified by onConnect( ) is passed a success argument that indicates if the attempt succeeded (i.e., a connection has been established). If so, success is set to true. If the attempt failed (i.e., a connection timed out, was refused, or otherwise could not be established), the success argument is set to false. Note that ActionScript does not distinguish among network timeout, unknown host, refusal, or other common connection errors. Therefore, the callback handler may not be executed for up to a minute after the connect( ) command is issued, depending on the settings of the server involved in a connection attempt, the connection speed, network traffic, and so on.

Example

We use onConnect( ) to detect the success or failure of a connection attempt. In practice, we might use it to set a flag indicating that transmissions should begin if the connection was successful. We may also use onConnect( ) to execute fallback code when the connection fails, such as alerting the user to the problem's nature.

To respond to an onConnect( ) event, we must assign a custom function (i.e., our callback handler) to the onConnect property of an XMLSocket object. The following code assigns the function handleConnect( ) to mySocket's onConnect property. By updating the value of the text field status_txt, handleConnect( ) alerts the user that a connection has either succeeded or failed:

mySocket = new XMLSocket();
mySocket.onConnect = handleConnect;
   
function handleConnect (succeeded) {
  if (succeeded) {
    status_txt.text += ("Successfully connected.\n");
  } else {
    status_txt.text += ("Connection attempt failed.\n");
  }
}

For code showing the onConnect( ) handler used in a more complete system, see Example 18-11 under the XMLSocket class.

See Also

XMLSocket.connect( ), XMLSocket.onClose( ); Chapter 10


Table of Contents