refactored and simplified in order to close stream from client