def connect_to_nsqd(self, conn):
        if not self.is_running:
            return

        if conn in self.conns:
            self.logger.debug('[%s] already connected' % conn)
            return

        if conn in self.pending:
            self.logger.debug('[%s] already pending' % conn)
            return

        self.logger.debug('[%s] connecting...' % conn)

        conn.on_response.connect(self.handle_response)
        conn.on_error.connect(self.handle_error)
        conn.on_finish.connect(self.handle_finish)
        conn.on_requeue.connect(self.handle_requeue)
        conn.on_auth.connect(self.handle_auth)

        if self.max_concurrency:
            conn.on_message.connect(self.queue_message)
        else:
            conn.on_message.connect(self.handle_message)

        self.pending.add(conn)

        try:
            conn.connect()
            conn.identify()

            if conn.max_ready_count < self.max_in_flight:
                msg = ' '.join([
                    '[%s] max RDY count %d < reader max in flight %d,',
                    'truncation possible'
                ])

                self.logger.warning(msg % (
                    conn,
                    conn.max_ready_count,
                    self.max_in_flight
                ))

            conn.subscribe(self.topic, self.channel)
            self.send_ready(conn, 1)

        except NSQException as error:
            self.logger.warn('[%s] connection failed (%r)' % (conn, error))
            self.handle_connection_failure(conn)
            return

        finally:
            self.pending.remove(conn)

        # Check if we've closed since we started
        if not self.is_running:
            conn.close_stream()
            return

        self.logger.info('[%s] connection successful' % conn)
        self.handle_connection_success(conn)
dataset/ETHPy150Open wtolson/gnsq/gnsq/reader.py/Reader.connect_to_nsqd/original