Tidied up server connection code and implemented automatic reconnecting.