correctly close connection/stream