Improved connection handling, added timeout detection and auto-reconnect