This method is called by pika once the connection to RabbitMQ has
        been established.

        :type connection: pika.TornadoConnection
357138
def on_connection_open(self, connection):
        
        LOGGER.debug('Connection opened')
        connection.add_on_connection_blocked_callback(
            self.on_connection_blocked)
        connection.add_on_connection_unblocked_callback(
            self.on_connection_unblocked)
        connection.add_backpressure_callback(self.on_back_pressure_detected)
        self.channel = self._open_channel()
416792
def connectionMade(self):
        
        self._buffer = b''
        self._queue = {}
        self._stopped = None
        self._tag = 0
592103
def __bind(self):
        '''
        
        '''
        # using ZMQIOLoop since we *might* need zmq in there
        install_zmq()
        self.io_loop = ZMQDefaultLoop()
        self.io_loop.make_current()
        for req_channel in self.req_channels:
            req_channel.post_fork(self._handle_payload, io_loop=self.io_loop)  # TODO: cleaner? Maybe lazily?
        try:
            self.io_loop.start()
        except (KeyboardInterrupt, SystemExit):
            # Tornado knows what to do
            pass
713071
def connect(self):
        
        self.set_state(self.STATE_CONNECTING)
        self.handle = tornado_connection.TornadoConnection(
            self._connection_parameters,
            on_open_callback=self.on_open,
            on_open_error_callback=self.on_open_error,
            stop_ioloop_on_close=False,
            custom_ioloop=self.io_loop)
658110
def initiate_handshake(self, headers, timeout=None):
        
        io_loop = IOLoop.current()
        timeout = timeout or DEFAULT_INIT_TIMEOUT_SECS

        self.writer.put(messages.InitRequestMessage(
            version=PROTOCOL_VERSION,
            headers=headers
        ))

        init_res_future = self.reader.get()
        timeout_handle = io_loop.call_later(timeout, (
            lambda: init_res_future.set_exception(errors.TimeoutError(
                'Handshake with %s:%d timed out. Did not receive an INIT_RES '
                'after %s seconds' % (
                    self.remote_host, self.remote_host_port, str(timeout)
                )
            ))
        ))
        io_loop.add_future(
            init_res_future,
            (lambda _: io_loop.remove_timeout(timeout_handle)),
        )

        init_res = yield init_res_future
        if init_res.message_type != Types.INIT_RES:
            raise errors.UnexpectedError(
                "Expected handshake response, got %s" % repr(init_res)
            )
        self._extract_handshake_headers(init_res)
        self._handshake_performed = True

        # The receive loop is started only after the handshake has been
        # completed.
        self._loop()

        raise tornado.gen.Return(init_res)
994897
def send_message(self, message):
        ''' 

        '''
        try:
            if _message_test_port is not None:
                _message_test_port.sent.append(message)
            yield message.send(self)
        except (WebSocketClosedError, StreamClosedError): # Tornado 4.x may raise StreamClosedError
            # on_close() is / will be called anyway
            log.warning("Failed sending message as connection was closed")
        raise gen.Return(None)
196352
def connect(async = false)
      @connection_thread = Thread.new do
        @connection = TestConnection.new
        @global_channel.dispatch('pusher:connection_established', JSON.dump({'socket_id' => '123abc'}))
      end
      @connection_thread.run
      @connection_thread.join unless async
      return self
    end
768692
def stop(self):
        
        if self._http_server is not None:
            self._http_server.stop()
        tornado.ioloop.IOLoop.instance().add_callback(
            tornado.ioloop.IOLoop.instance().stop)
12653
def send(self, msg, timeout=None, callback=None, raw=False):
        '''
        
        '''
        message_id = self._message_id()
        header = {'mid': message_id}

        future = tornado.concurrent.Future()
        if callback is not None:
            def handle_future(future):
                response = future.result()
                self.io_loop.add_callback(callback, response)
            future.add_done_callback(handle_future)
        # Add this future to the mapping
        self.send_future_map[message_id] = future

        if self.opts.get('detect_mode') is True:
            timeout = 1

        if timeout is not None:
            send_timeout = self.io_loop.call_later(timeout, self.timeout_message, message_id)
            self.send_timeout_map[message_id] = send_timeout

        # if we don't have a send queue, we need to spawn the callback to do the sending
        if not self.send_queue:
            self.io_loop.spawn_callback(self._stream_send)
        self.send_queue.append((message_id, salt.transport.frame.frame_msg(msg, header=header)))
        return future
408400
def connect(self, *args, auto_reconnect=False, **kwargs):
        
        connection_info = {
            'auto_reconnect': auto_reconnect,
            'args': args,
            'kwargs': kwargs,
        }
        self.connect_info['connection'] = connection_info

        # confirm we have user info set
        if 'user' not in self.connect_info:
            raise Exception('`set_user_info` must be called before connecting to server.')

        # create connection and run
        connection = loop.create_connection(lambda: self,
                                            *args, **kwargs)
        asyncio.Task(connection)
465916
def on_connection_open_error(self, connection, error):
        
        LOGGER.critical('Could not connect to RabbitMQ (%s): %r',
                        connection, error)
        self.state = self.STATE_CLOSED
        self._reconnect()
749726
async def connect(self, req: 'ClientRequest',
                      traces: List['Trace'],
                      timeout: 'ClientTimeout') -> Connection:
        """"""
        key = req.connection_key
        available = self._available_connections(key)

        # Wait if there are no available connections.
        if available <= 0:
            fut = self._loop.create_future()

            # This connection will now count towards the limit.
            waiters = self._waiters[key]
            waiters.append(fut)

            if traces:
                for trace in traces:
                    await trace.send_connection_queued_start()

            try:
                await fut
            except BaseException as e:
                # remove a waiter even if it was cancelled, normally it's
                #  removed when it's notified
                try:
                    waiters.remove(fut)
                except ValueError:  # fut may no longer be in list
                    pass

                raise e
            finally:
                if not waiters:
                    try:
                        del self._waiters[key]
                    except KeyError:
                        # the key was evicted before.
                        pass

            if traces:
                for trace in traces:
                    await trace.send_connection_queued_end()

        proto = self._get(key)
        if proto is None:
            placeholder = cast(ResponseHandler, _TransportPlaceholder())
            self._acquired.add(placeholder)
            self._acquired_per_host[key].add(placeholder)

            if traces:
                for trace in traces:
                    await trace.send_connection_create_start()

            try:
                proto = await self._create_connection(req, traces, timeout)
                if self._closed:
                    proto.close()
                    raise ClientConnectionError("Connector is closed.")
            except BaseException:
                if not self._closed:
                    self._acquired.remove(placeholder)
                    self._drop_acquired_per_host(key, placeholder)
                    self._release_waiter()
                raise
            else:
                if not self._closed:
                    self._acquired.remove(placeholder)
                    self._drop_acquired_per_host(key, placeholder)

            if traces:
                for trace in traces:
                    await trace.send_connection_create_end()
        else:
            if traces:
                for trace in traces:
                    await trace.send_connection_reuseconn()

        self._acquired.add(proto)
        self._acquired_per_host[key].add(proto)
        return Connection(self, key, proto, self._loop)
431599
def _connect(self):
        
        future = concurrent.Future()

        # Attempt to get a cached connection from the connection pool
        try:
            connection = self._pool_manager.get(self.pid, self)
            self._connections[connection.fileno()] = connection
            future.set_result(connection)

            # Add the connection to the IOLoop
            self._ioloop.add_handler(connection.fileno(),
                                     self._on_io_events,
                                     ioloop.IOLoop.WRITE)
        except pool.NoIdleConnectionsError:
            self._create_connection(future)

        return future
1294295
def connect(self):
        
        future = concurrent.Future()

        if self.connected:
            raise exceptions.ConnectError('already connected')

        LOGGER.debug('%s connecting', self.name)
        self.io_loop.add_future(
            self._client.connect(self.host, self.port),
            lambda f: self._on_connected(f, future))
        return future
29457
protected void nowReconnectedSync(IOException originalExcep) throws IOException {

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Reconnected sync for " + this);
        }
        if (!resetWriteBuffers()) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Resetting buffers (sync) failed");
            }
            throw originalExcep;
        }
        // now that we've reconnected, we should reset the "broken" flag. First
        // we set it to the default and then recheck the request msg
        setPersistent(true);
        updatePersistence(getRequestImpl());

        // Note: during a sync path, we don't actually enable reconnects once
        // we start reading and parsing the response (only async path)
        // in case we read any partial data, we need to clean out the response
        // resetRead();

        if (isReadAheadEnabled()) {
            // after a reconnect, there is no more read-ahead active
            this.bReadAheadEnabled = false;
        }
        try {
            getTSC().getWriteInterface().write(TCPWriteRequestContext.WRITE_ALL_DATA, getWriteTimeout());
        } catch (IOException ioe) {
            // no FFDC required
            // just set the "broken" connection flag
            setPersistent(false);
            throw ioe;
        }
    }
828799
private void actuallyReconnect() {
        if (((null == signalingChannel) || !signalingChannel.connected) && reconnect) {
            if (connectionInProgress) {
                // The client app must have initiated a connection manually during the timeout period. Try again later
                performReconnect();
            } else {
                Log.d(TAG, "Trying to reconnect...");
                connect(localEndpointID, applicationID, reconnect, presence, appContext, new ConnectCompletionListener() {
                    @Override
                    public void onError(final String errorMessage) {
                        // A REST API call failed. Socket errors are handled in the onError callback
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                Listener listener = listenerReference.get();
                                if (null != listener) {
                                    listener.onError(RespokeClient.this, errorMessage);
                                }
                            }
                        });

                        // Try again later
                        performReconnect();
                    }
                });
            }
        }
    }
1009857
def connections(self, wait):
        
        while wait:
            try:
                params = pika.ConnectionParameters(host=self.rmq_host,
                                                   port=self.rmq_port)
                connection = pika.BlockingConnection(params)
                self.channel = connection.channel()
                self.channel.exchange_declare(exchange='topic_recs',
                                              exchange_type='topic')

                result = self.channel.queue_declare()
                self.queue_name = result.method.queue
                self.es_conn = Elasticsearch([{'host': self.es_host,
                                               'port': self.es_port}])
                wait = False
                print('connected to rabbitmq and elasticsearch...')
            except Exception as e:  # pragma: no cover
                print(str(e))
                print('waiting for connection to rabbitmq...' + str(e))
                time.sleep(2)
                wait = True