Centralizes socket state detection

This commit centralizes the detection of the socket being connected or
disconnected. Thus, individual scripts do not need to test for the state
before attempting to use the socket. This also fixes a problem where
the socket was being opened multiple times.