Fix some socket and thread bugs

Now it can be switched between connect and disconnect stably.