Recipe 24.6.
Handling Socket Errors
Problem
You want
to handle errors that might occur when using sockets.
Solution
Use try/catch to handle I/O and end
of file (EOF) errors.
Discussion
Both the Socket and XMLSocket
classes behave similarly in regard to errors and error events. When
calling the connect( ) method, Socket and
XMLSocket objects can throw an error of type
SecurityError when either of the following conditions is
true:
When calling send( ) (XMLSocket) or
flush( ) (Socket), the method can throw an error of
type IOError if the socket isn't connected. Although you can
(and likely should) place the send( ) or flush( )
method calls within try/catch blocks, you should not rely on
try/catch blocks as part of your application logic. Rather, use an
if statement to test whether or not the socket object's connected
property is true before calling send( ) of flush( )
if you want such a test to be part of the application logic. For
example, the following uses an if statement as part of the
application logic to call a connectToSocketServer( ) method
if the Socket object isn't currently connected. It also uses
a TRy/catch block to write to a log if the
flush( ) method throws an error:
if ( socket.connected ) {
try {
socket.flush( );
}
catch( error:IOError ) {
logInstance.write( "socket.flush error\n" + error );
}
}
else {
connectToSocketServer( );
}
All of the Socket read methods
can throw errors of type EOFError and IOError. EOF
errors occur when you try to read data, but nothing is available.
I/O errors occur when you try to read from a socket that is
closed.
In addition to the errors thrown by methods of
the Socket and XMLSocket classes, objects of those
classes also dispatch error events. There are two basic types of
error events that occur with socketsIOError and
securityError. The IOError event is of type
IOErrorEvent, and it occurs when data fails to send or load.
The securityError event is of type
SecurityErrorEvent, and it occurs when a socket attempts to
connect to a server but fails because the server is either outside
of the sandbox or because the port number is lower than
1024.
|
Both security error event scenarios are
correctable by way of a cross-domain policy file.
|
|
|