Handling websocket close plus minor refactoring and tests.