Handle socket closing and error opening