complete rewrite of connection management / watchdog code

Added StateManager and ConnectionManager classes (and related
data classes) to make state and connection management operations
explicit and (where feasible) thread-safe.

The watchdog is now very careful not to interrupt the
server loop thread unless it is explicitly blocked waiting
for a keepalive signal.  I'm hoping this fixes errors I have
seen where the watchdog starts killing the server loop
even when it is not connected.