Performs the actual connection, retrying, generating the
        authorization key if necessary, and starting the send and
        receive loops.
8329
async def _connect(self):
        
        self._log.info('Connecting to %s...', self._connection)
        for attempt in retry_range(self._retries):
            try:
                self._log.debug('Connection attempt {}...'.format(attempt))
                await self._connection.connect(timeout=self._connect_timeout)
            except (IOError, asyncio.TimeoutError) as e:
                self._log.warning('Attempt {} at connecting failed: {}: {}'
                                  .format(attempt, type(e).__name__, e))
                await asyncio.sleep(self._delay)
            else:
                break
        else:
            raise ConnectionError('Connection to Telegram failed {} time(s)'
                                  .format(attempt))

        self._log.debug('Connection success!')
        if not self.auth_key:
            plain = MTProtoPlainSender(self._connection, loggers=self._loggers)
            for attempt in retry_range(self._retries):
                try:
                    self._log.debug('New auth_key attempt {}...'
                                    .format(attempt))
                    self.auth_key.key, self._state.time_offset =\
                        await authenticator.do_authentication(plain)

                    # This is *EXTREMELY* important since we don't control
                    # external references to the authorization key, we must
                    # notify whenever we change it. This is crucial when we
                    # switch to different data centers.
                    if self._auth_key_callback:
                        self._auth_key_callback(self.auth_key)

                    break
                except (SecurityError, AssertionError) as e:
                    self._log.warning('Attempt {} at new auth_key failed: {}'
                                      .format(attempt, e))
                    await asyncio.sleep(self._delay)
            else:
                e = ConnectionError('auth_key generation failed {} time(s)'
                                    .format(attempt))
                await self._disconnect(error=e)
                raise e

        self._log.debug('Starting send loop')
        self._send_loop_handle = self._loop.create_task(self._send_loop())

        self._log.debug('Starting receive loop')
        self._recv_loop_handle = self._loop.create_task(self._recv_loop())

        # _disconnected only completes after manual disconnection
        # or errors after which the sender cannot continue such
        # as failing to reconnect or any unexpected error.
        if self._disconnected.done():
            self._disconnected = self._loop.create_future()

        self._log.info('Connection to %s complete!', self._connection)
110483
def run(self):
        

        while self.__nice_quit_ev.is_set() is False:
            self.__connect()

        _logger.info("Connection re-connect loop has terminated: %s", self.__mc)
319306
public void run()
    {
        // respond to the request that triggered this validation
        if (!initiator.equals(FBUtilities.getBroadcastAddress()))
            logger.info(String.format("[repair #%s] Sending completed merkle tree to %s for %s/%s", desc.sessionId, initiator, desc.keyspace, desc.columnFamily));
        MessagingService.instance().sendOneWay(new ValidationComplete(desc, tree).createMessage(), initiator);
    }
669566
def run( self ):
        

        self.handshake()

        try:
            self.loop()
        except socket.error, se:
            if self.finished:
                return True
            else:
                raise
833828
protected synchronized void connect()
    {
        if (api.getStatus() != JDA.Status.ATTEMPTING_TO_RECONNECT)
            api.setStatus(JDA.Status.CONNECTING_TO_WEBSOCKET);
        if (shutdown)
            throw new RejectedExecutionException("JDA is shutdown!");
        initiating = true;

        String url = api.getGatewayUrl() + "?encoding=json&v=" + DISCORD_GATEWAY_VERSION;
        if (compression)
        {
            url += "&compress=zlib-stream";
            decompressBuffer = newDecompressBuffer();
        }

        try
        {
            socket = api.getWebSocketFactory()
                    .createSocket(url)
                    .addHeader("Accept-Encoding", "gzip")
                    .addListener(this);
            socket.connect();
        }
        catch (IOException | WebSocketException e)
        {
            api.resetGatewayUrl();
            //Completely fail here. We couldn't make the connection.
            throw new IllegalStateException(e);
        }
    }
247676
def start(self):
        """"""
        if self.state != STATE_RUNNING:
            conn = self.loop.create_connection(
                lambda: self, self.host, self.port)
            task = self.loop.create_task(conn)
            task.add_done_callback(self.init_done)
            self.state = STATE_STARTING
829828
private void setHandshakeSuccess() {
        handshakePromise.trySuccess(ctx.channel());

        if (logger.isDebugEnabled()) {
            logger.debug("{} HANDSHAKEN: {}", ctx.channel(), engine.getSession().getCipherSuite());
        }
        ctx.fireUserEventTriggered(SslHandshakeCompletionEvent.SUCCESS);

        if (readDuringHandshake && !ctx.channel().config().isAutoRead()) {
            readDuringHandshake = false;
            ctx.read();
        }
    }
1344462
def perform(req, options)
      verify_connection!(req.uri)

      @state = :dirty

      @connection ||= HTTP::Connection.new(req, options)

      unless @connection.failed_proxy_connect?
        @connection.send_request(req)
        @connection.read_headers!
      end

      res = Response.new(
        :status        => @connection.status_code,
        :version       => @connection.http_version,
        :headers       => @connection.headers,
        :proxy_headers => @connection.proxy_response_headers,
        :connection    => @connection,
        :encoding      => options.encoding,
        :uri           => req.uri
      )

      res = options.features.inject(res) do |response, (_name, feature)|
        feature.wrap_response(response)
      end

      @connection.finish_response if req.verb == :head
      @state = :clean

      res
    rescue
      close
      raise
    end
524092
def start(self):
        '''
        
        '''
        # Start suicide polling thread
        log.debug('Starting the auth process')
        self.verify_cert()
        self._create_skt()
        log.debug('The auth process can receive at most %d parallel connections', AUTH_MAX_CONN)
        self.socket.listen(AUTH_MAX_CONN)
        thread = threading.Thread(target=self._suicide_when_without_parent, args=(os.getppid(),))
        thread.start()
        signal.signal(signal.SIGTERM, self._exit_gracefully)
        self.__up = True
        while self.__up:
            try:
                (clientsocket, address) = self.socket.accept()
                wrapped_auth_skt = ssl.wrap_socket(clientsocket,
                                                   server_side=True,
                                                   certfile=self.certificate,
                                                   keyfile=self.keyfile)
            except ssl.SSLError:
                log.exception('SSL error', exc_info=True)
                continue
            except socket.error as error:
                if self.__up is False:
                    return
                else:
                    msg = 'Received auth socket error: {}'.format(error)
                    log.error(msg, exc_info=True)
                    raise NapalmLogsExit(msg)
            log.info('%s connected', address)
            log.debug('Starting the handshake')
            client_thread = threading.Thread(target=self._handshake,
                                             args=(wrapped_auth_skt, address))
            client_thread.start()
830723
public synchronized void connectionEstablished (
        PresentsConnection conn, Name authname, AuthRequest req, AuthResponse rsp)
    {
        String type = authname.getClass().getSimpleName();

        // see if a session is already registered with this name
        PresentsSession session = getClient(authname);

        if (session != null) {
            //log.info("Resuming session", "type", type, "who", authname, "conn", conn);
            session.resumeSession(req, conn);

        } else {
            log.info("Session initiated", "type", type, "who", authname, "conn", conn);
            // figure out our session class
            Class<? extends PresentsSession> sessionClass = null;
            for (SessionFactory factory : _factories) {
                if ((sessionClass = factory.getSessionClass(req)) != null) {
                    break;
                }
            }
            // create a new session and stick'em in the table
            session = _injector.getInstance(sessionClass);
            session.startSession(authname, req, conn, rsp.authdata);

            // map their session instance
            synchronized (_usermap) {
                // we refetch the authname from the session for use in the map in case it decides
                // to do something crazy like rewrite it in startSession()
                _usermap.put(session.getAuthName(), session);
            }
        }

        // map this connection to this session
        _conmap.put(conn, session);
    }
480592
def run(self):
        
        while not self._request_shutdown:

            # Find out if we have any data pending from the
            # server
            try:

                # If we've been asked to stop running the
                # request loop. We'll just sit and wait
                # till we get asked to run again
                if self._state not in [STATE_AUTHENTICATING,STATE_WEBSOCKET_CONNECTED,STATE_CONNECTED]:
                    self._request_loop_notify_restart.acquire()
                    self._request_loop_notify_restart.wait(self._loop_timeout)
                    self._request_loop_notify_restart.release()
                    continue

                # If we don't have a websocket defined.
                # we don't go further either
                elif not self.ws:
                    logger.debug("No longer have a websocket. Marking disconnected")
                    self._state = STATE_DISCONNECTED
                    continue

                # Okay, we think we're okay so let's try and read some data
                data = self.ws.recv()
            except io.BlockingIOError:
                continue
            except websocket.WebSocketTimeoutException:
                continue
            except websocket.WebSocketConnectionClosedException as ex:
                logger.debug("WebSocketConnectionClosedException: Requesting disconnect:".format(ex))
                self.disconnect()

                # If the server disconnected, let's try and reconnect
                # back to the service after a random few seconds
                if self.auto_reconnect:
                    # As doing a reconnect would block and would then
                    # prevent us from ticking the websoocket, we'll
                    # go into a subthread to deal with the reconnection
                    def reconnect():
                        self.reconnect()
                    t = threading.Thread(target=reconnect)
                    t.start()

                    # FIXME: need to randomly wait
                    time.sleep(1)
                    if not data: continue
            except Exception as ex:
                logger.error("ERROR in main loop: {}".format(ex))
                continue

            try:
                logger.debug("<RCV: {}".format(data))
                message = WampMessage.loads(data)
                logger.debug("<RCV: {}".format(message.dump()))
                try:
                    code_name = message.code_name.lower()
                    handler_name = "handle_"+code_name
                    handler_function = getattr(self,handler_name)
                    handler_function(message)
                except AttributeError as ex:
                    self.handle_unknown(message)
            except Exception as ex:
                logger.error("ERROR in main loop: {}".format(ex))
764197
@Override
    protected boolean performRequest() {
        VirtualConnection vci = null;
        boolean completeOperation = true;
        TCPBaseRequestContext req = null;
        SelectionKey selectedKey = null;

        // If we were woken up because we have work to do, do it.
        Set<SelectionKey> keySet = selector.selectedKeys();
        Iterator<SelectionKey> selectedIterator = keySet.iterator();
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(this, tc, "performRequest - processing " + keySet.size() + " items");
        }
        while (selectedIterator.hasNext()) {
            selectedKey = selectedIterator.next();
            // safely remove from set while looping
            selectedIterator.remove();
            req = (TCPBaseRequestContext) selectedKey.attachment();
            vci = req.getTCPConnLink().getVirtualConnection();
            completeOperation = true;

            // looking at the vci is messy here, but we're doing the try, catch
            // to save synchronization logic. vci could be null if connection
            // is closing before we can asked to request permission to finish
            // the read.
            if (vci == null) {
                completeOperation = false;
            } else {
                // only check if operation was an async read/write request
                if (vci.isInputStateTrackingOperational() && !req.blockedThread) {
                    completeOperation = false;
                    if (req.isRequestTypeRead()) {
                        if (vci.requestPermissionToFinishRead()) {
                            completeOperation = true;
                        }
                    } else {
                        if (vci.requestPermissionToFinishWrite()) {
                            completeOperation = true;
                        }
                    }
                }
            }

            if (completeOperation) {
                // try to dispatch request. if it fails, just leave key alone,
                // and it should get selected and tried again the next time through
                // the selector.
                if (wqm.dispatch(req, null)) {
                    // Dispatch worked, so set key's interest set to empty, so it isn't
                    // re-selected
                    // until the user asks us to do more work.
                    try {
                        selectedKey.interestOps(0);
                    } catch (CancelledKeyException cke) {
                        // ignore, since we already got the key and the data
                    }
                }
            } else {
                // permission denied, assume close has been processed on this VC
                // therefore disregard this read.
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                    Tr.event(this, tc, "IO cancelled on closed key " + selectedKey);
                }
                try {
                    selectedKey.interestOps(0);
                } catch (CancelledKeyException cke) {
                    // ignore, since the vc is closed/ing
                }
            }
        }

        return false;
    }
318476
@Override
	public void run() {
		if (logger.isInfoEnabled()) {
			logger.info(String.format("SelectorThread for Management=%s started.", this.management.getName()));
		}
		while (this.started) {
			try {
				FastList<ChangeRequest> pendingChanges = this.management.getPendingChanges();

				// Process any pending changes
				synchronized (pendingChanges) {
					Iterator<ChangeRequest> changes = pendingChanges.iterator();
					while (changes.hasNext()) {
						ChangeRequest change = changes.next();
						switch (change.getType()) {
						case ChangeRequest.CHANGEOPS:
							pendingChanges.remove(change);
							SelectionKey key = change.getSocketChannel().keyFor(this.selector);
							key.interestOps(change.getOps());
							break;
						case ChangeRequest.REGISTER:
							pendingChanges.remove(change);
							SelectionKey key1 = change.getSocketChannel().register(this.selector, change.getOps());
							key1.attach(change.getAssociation());
							break;
						case ChangeRequest.CONNECT:
							if (!change.getAssociation().isStarted()) {
								// if Association is stopped - remove pending connection requests  
								pendingChanges.remove(change);
							} else {
								if (change.getExecutionTime() <= System.currentTimeMillis()) {
									pendingChanges.remove(change);
									change.getAssociation().initiateConnection();
								}
							}
							break;
						case ChangeRequest.CLOSE:
							pendingChanges.remove(change);
							change.getAssociation().close();
						}
					}// end of while
				}

				// Wait for an event one of the registered channels
				this.selector.select(500);

				// System.out.println("Done selecting " +
				// this.selector.selectedKeys().size());

				// Iterate over the set of keys for which events are available
				Iterator<SelectionKey> selectedKeys = this.selector.selectedKeys().iterator();

				while (selectedKeys.hasNext()) {
					SelectionKey key = selectedKeys.next();
					selectedKeys.remove();

					if (!key.isValid()) {
						continue;
					}

					// Check what event is available and deal with it
					if (key.isConnectable()) {
						this.finishConnection(key);
					} else if (key.isAcceptable()) {
						this.accept(key);
					} else if (key.isReadable()) {
						this.read(key);
					} else if (key.isWritable()) {
						this.write(key);
					}
				}

			} catch (Exception e) {
				logger.error("Error while selecting the ready keys", e);
			}
		}

		try {
			this.selector.close();
		} catch (IOException e) {
			logger.error(String.format("Error while closing Selector for SCTP Management=%s", this.management.getName()));
		}

		if (logger.isInfoEnabled()) {
			logger.info(String.format("SelectorThread for Management=%s stopped.", this.management.getName()));
		}
	}
1010002
@Override
  public void run() {
    while (running) {
      try {
        handleIO();
      } catch (IOException e) {
        logRunException(e);
      } catch (CancelledKeyException e) {
        logRunException(e);
      } catch (ClosedSelectorException e) {
        logRunException(e);
      } catch (IllegalStateException e) {
        logRunException(e);
      } catch (ConcurrentModificationException e) {
        logRunException(e);
      }
    }
    getLogger().info("Shut down memcached client");
  }
1051911
private void restartPreviousConnection() throws CommunicationException, KeystoreException {
		try {
			logger.debug("Closing connection to restart previous one");
			this.socket.close();
		} catch (Exception e) {
			/* Do not complain if connection is already closed... */
		}
		initializePreviousConnection();
	}
1214662
function Connection (options) {
  options = utils.clone(options || {});

  var ns = this._ns = utils.createNamespace(options);
  var id = this.id = options.id || utils.uniqueId('connection');
  this._debug = utils.debug('connection:' + id);
  var me = this;

  // create controller connection
  this._host = options.host || define.host;
  this._port = options.port || define.port;
  process.nextTick(function () {
    me._debug('trying reconnect');
    me._reconnect();
  });

  me._queue = [];
  ['send', 'registerKey', 'deleteKey', 'deleteKeys', 'keys'].forEach(function (method) {
    me[method] = me._wrapMethod(me[method], method);
  });
  me.on('ready', function () {
    me._debug('emit listen');
    me.emit('listen');
    me._processQueue();
  });
}
870374
def run(request)
      util = logger
      util.debug { request.log_string }
      response = request.run(raw_connection)
      util.debug { response.status.to_s }
      response
    end