Adding connection state checking and reconnection logic for writing to connection