Modified to better handle socket cleanup.