Rewritten SocketThreads for proper shutdown scenario.

This fixes #560 and #390.