You are here

function httprl_establish_stream_connection in HTTP Parallel Request & Threading Library 7

Same name and namespace in other branches
  1. 6 httprl.module \httprl_establish_stream_connection()

Use stream_socket_client() to create a connection to the server.

Parameters

object $result: A object to hold the result values.

1 call to httprl_establish_stream_connection()
httprl_send_request in ./httprl.module
Perform many HTTP requests.

File

./httprl.module, line 1020
HTTP Parallel Request Library module.

Code

function httprl_establish_stream_connection(&$result) {

  // Record start time.
  $start_time = microtime(TRUE);
  $result->fp = FALSE;

  // Try to make a connection, 3 max tries in loop.
  $count = 0;
  while (!$result->fp && $count < 3) {

    // Try the connection again not using async if in https mode.
    if ($count > 0) {
      if ($result->flags === STREAM_CLIENT_ASYNC_CONNECT | STREAM_CLIENT_CONNECT && $result->uri['scheme'] == 'https') {
        $result->flags = STREAM_CLIENT_CONNECT;
        $result->options['async_connect'] = FALSE;
      }
      else {

        // Break out of while loop if we can't connect.
        break;
      }
    }

    // Set the DNS timeout.
    $timeout = $result->options['dns_timeout'];

    // If not using async_connect then add connect_timeout to timeout.
    if (!$result->options['async_connect']) {
      $timeout += $result->options['connect_timeout'];
    }

    // Open the connection.
    if (empty($result->options['context'])) {
      $result->fp = @stream_socket_client($result->socket, $errno, $errstr, $timeout, $result->flags);
    }
    else {

      // Create a stream with context. Context allows for the verification of
      // a SSL certificate.
      $result->fp = @stream_socket_client($result->socket, $errno, $errstr, $timeout, $result->flags, $result->options['context']);
    }
    $count++;
  }

  // Make sure the stream opened properly. This check doesn't work if
  // async_connect is used, so only check it if async_connect is FALSE. Making
  // sure that stream_socket_get_name returns a "TRUE" value.
  if ($result->fp && !$result->options['async_connect'] && !stream_socket_get_name($result->fp, TRUE)) {
    $errno = HTTPRL_CONNECTION_REFUSED;
    $errstr = 'Connection refused. No connection could be made because the target machine actively refused it.';
    $result->fp = FALSE;
  }

  // Report any errors or set the stream to non blocking mode.
  if (!$result->fp) {
    httprl_stream_connection_error_formatter($errno, $errstr, $result);
  }
  else {
    stream_set_blocking($result->fp, 0);
  }

  // Record end time.
  $end_time = microtime(TRUE);
  $extra = 0;
  if (isset($result->options['internal_states']['running_time'])) {
    $extra = $result->options['internal_states']['running_time'];
    unset($result->options['internal_states']['running_time']);
  }
  $result->running_time = $end_time - $start_time + $extra;
}