Fixed the bug, which was a cause of crashes of the client in some cases of lost connection; slight refactoring and optimization