Fix for issue #246: Connection does not close cleanly