Sockets: when and how to close them?

Simon Marlow simonmar@microsoft.com
Wed, 7 Nov 2001 14:08:26 -0000


> When using Sockets, exactly when and where do I have to close them?
>=20
> The documentation (of module Socket) implies that this is not=20
> necessary?
> However there is sClose in SocketPrim. My application is one Server
> who runs `listenOn' and many (short lived) clients that `connectTo'.
> After I run this for a while, netstat typically says
>=20
> autotool@isun11:~/autotool/serial$ netstat|grep local
> localhost.9121       localhost.56749      32768      0 32768 =20
>     0 CLOSE_WAIT
> localhost.56749      localhost.9121       32768      0 32768 =20
>     0 FIN_WAIT_2
> localhost.9121       localhost.56753      32768      0 32768 =20
>     0 CLOSE_WAIT
> localhost.56753      localhost.9121       32768      0 32768 =20
>     0 FIN_WAIT_2

If your sockets are in the form of Handles, i.e. if you used
Socket.connectTo rather than the raw version in SocketPrim, then they
will be closed automatically by the standard Handle finalizer mechanism.
It is good practice, however, to close them as soon as you know you no
longer need them (using hClose) as this will free up the resources
immediately.

Sockets returned from Socket.listenOn or from the low level routines in
SocketPrim must be closed by hand using SocketPrim.sClose.  It is
probably a bug that Socket doesn't export sClose.

Cheers,
	Simon