Close socket and move 'remove handler' statement to the end of run()