Reorganized socket close handler on server side in an attempt to make it safer