Skip to content

Commit

Permalink
Merge pull request #29 from ins0/fix/26
Browse files Browse the repository at this point in the history
Fix/26
  • Loading branch information
ins0 committed Mar 23, 2016
2 parents 672502d + c375eb3 commit e3d8948
Showing 1 changed file with 20 additions and 16 deletions.
36 changes: 20 additions & 16 deletions src/Racecore/GATracking/Client/Adapter/Socket.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@

class Socket extends Client\AbstractClientAdapter
{
const READ_TIMEOUT = 3;
const READ_BUFFER = 8192;

private $connection = null;

/**
Expand All @@ -20,15 +23,16 @@ private function createConenction($endpoint)
// port
$port = $this->getOption('ssl') == true ? 443 : 80;

// connect
$connection = @fsockopen($port == 443 ? 'ssl://' . $endpoint['host'] : $endpoint['host'], $port, $error, $errorMessage, 10);
$connection = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($connection, $endpoint['host'], $port);
socket_set_option($connection, SOL_SOCKET, SO_RCVTIMEO, array('sec' => self::READ_TIMEOUT, 'usec' => 0));

if (!$connection || $error) {
throw new Exception\EndpointServerException('Analytics Host not reachable! Error:' . $errorMessage);
if ($this->getOption('async')) {
socket_set_nonblock($connection);
}

if ($this->getOption('async')) {
stream_set_blocking($connection, 0);
if (!$connection) {
throw new Exception\EndpointServerException('Analytics Host not reachable! Error:');
}

$this->connection = $connection;
Expand All @@ -55,7 +59,7 @@ private function writeHeader($endpoint, Request\TrackingRequest $request, $lastD
($lastData ? 'Connection: Close' . "\r\n" : '') . "\r\n";

// fwrite + check if fwrite was ok
if (!fwrite($this->connection, $header) || !fwrite($this->connection, $payloadString)) {
if (!socket_write($this->connection, $header) || !socket_write($this->connection, $payloadString)) {
throw new Exception\EndpointServerException('Server closed connection unexpectedly');
}

Expand All @@ -69,17 +73,18 @@ private function writeHeader($endpoint, Request\TrackingRequest $request, $lastD
*/
private function readConnection(Request\TrackingRequest $request)
{
if ($this->getOption('async')) {
return false;
}

// response
$response = '';

// receive response
while (!feof($this->connection)) {
$response .= fread($this->connection, 8192);
}
do {
$out = @socket_read($this->connection, self::READ_BUFFER);
$response .= $out;

if (!$out || strlen($out) < self::READ_BUFFER) {
break;
}
} while (true);

// response
$responseContainer = explode("\r\n\r\n", $response, 2);
Expand Down Expand Up @@ -110,9 +115,8 @@ public function send($url, Request\TrackingRequestCollection $requestCollection)

$request->setResponseHeader($responseHeader);
}

// connection close
fclose($this->connection);
socket_close($this->connection);

return $requestCollection;
}
Expand Down

0 comments on commit e3d8948

Please sign in to comment.