Close outgoing socket (fixes #559)

Note that this includes #560.