The key is to listen to the Socket object for the event IOErrorEvent.IO_ERROR
. In the case you're referring to, where the connection is denied immediately, this event will be triggered immediately. In fact, it can be triggered so quickly that you will miss it unless you do things in the proper order (as shown here):
// first create the unconnected socket, and add the listener
// you *must* add the listener *before* connecting the socket
//
var mySocket = new Socket();
mySocket.addEventListener(IOErrorEvent.IO_ERROR, function(event:IOErrorEvent):void {
// called when error occurrs
trace("ioErrorHandler: " + event);
});
mySocket.addEventListener(flash.events.Event.CONNECT, function(event:Event):void {
// handle a successful connection here
//...
});
// now initiate the connection to port 80 on "server.example.com"
mySocket.connect( 'server.example.com', 80 );
NOTE: this approach is not based on a timeout. If the server returns a definite "connection refused" response then the IO Error event will happen immediately when that response is received.
The timeout only applies when the server returns nothing for an extended period of time. This can happen with certain server/firewall configurations that actually drop packets silently rather than returning "connection refused". When this happens, the client (in this case Flash), will sit waiting until the timeout expires. When the timeout does finally expire, it will result in an IOErrorEvent.IO_ERROR
event as you would expect.
The default socket timeout is platform-dependent but it's always fairly long (~20-30 seconds or more). The Socket.timeout
property is introduced in Flash Player version 10 and Air 1.0. As far as I know, there is no way to adjust the the socket timeout using ActionScript prior to Flash Player 10.
good luck!
--- EDIT: if it's still not working, read on ---
You should also be familiar with the way the flash player looks for (and requires) a socket policy file. Missing, or broken Socket Policy Files can sometime produce behavior that looks like a socket waiting on timeout. Quoting from this Adobe Document:
Access to socket and XML socket connections is disabled by default, even if the socket
you are connecting to is in the same domain as the SWF file. You can permit socket-level
access by serving a socket policy file from any of the following locations:
- Port 843 (the location of the master policy file)
- The same port as the main socket connection
- A different port than the main socket connection
This means that, unless you have previously loaded a policy file using Security.loadPolicyFile()
, when you initially try to connect your socket to the server, flash will first try to resolve a policy file. In some cases this can result in strange connection delays or other unexpected behavior. If you think you may be encountering this problem, you should start by adding a listener for flash.events.SecurityErrorEvent.SECURITY_ERROR
.