Flushed the socket before it ends

Fixes #445 and #422.