Fix/handle sudden disconnection

Fixes #369