Recipe 24.5.
Disconnecting from a Socket Server
Problem
You want
to disconnect from a socket server, or be notified when the server
disconnects you.
Solution
Invoke the Socket.close( ) or XMLSocket.close( ) method
to explicitly close the
connection, or listen for the close event to be notified
when the server closes the connection for you.
Discussion
A general rule to follow when programming is to
clean up after yourself. That is, if you create an object, you
should also delete it when it is no longer necessary. In this case,
whenever you connect to a socket server, you should explicitly
close the connection when you're done. Leaving an unused socket
connection open is a waste of resources and should be avoided if at
all possible. If you don't close a connection, then the server may
continue to keep an open socket connection that is not being used,
which can quickly cause a server to overrun its allotment of
allowed socket connections.
Closing a socket connection is the same for both
Socket and XMLSocket instances. All you need to do is
invoke the close( )
method on the socket instance:
// Assume socket is a connected Socket instance
socket.close( ); // Disconnect from the server
Using an XMLSocket is exactly the
same:
// Assume xmlSocket is a connected XMLSocket instance
xmlSocket.close( ); // Disconnect from the server
The close( ) method is useful for letting
the server know that the client wants to disconnect. To be notified
when the server closes the connection on its own, you should listen
for the close event by calling addEventListener( )
on the Socket or XMLSocket instance with
Event.CLOSE as the event type; for example:
var socket:Socket = new Socket( );
// Add an event listener to be notified when the server disconnects
// the client
socket.addEventListener( Event.CLOSE, onClose );
|
Invoking the close( ) method does not
raise the close event. Instead, the close event
is raised only when the server initiates the disconnection.
|
|
Once a socket is closed, it is no longer capable
of reading or writing data. If you'd like to reuse the socket, you
have to establish a connection again as described in Recipe
24.1.
See Also
Recipe
24.1
|