Adding Omar's changes to close the socket more consistently.