Avoiding situation where socket could be closed twice