Skip to content

Commit

Permalink
Reduce the amount of garbage produced by TcpConnector on cancellation
Browse files Browse the repository at this point in the history
  • Loading branch information
valga committed Sep 1, 2017
1 parent ee817e3 commit cefad72
Showing 1 changed file with 12 additions and 27 deletions.
39 changes: 12 additions & 27 deletions src/TcpConnector.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,21 +90,26 @@ public function connect($uri)

// wait for connection

return $this
->waitForStreamOnce($socket)
->then(array($this, 'checkConnectedSocket'))
->then(array($this, 'handleConnectedSocket'));
return $this->waitForStreamOnce($socket);
}

private function waitForStreamOnce($stream)
{
$loop = $this->loop;

return new Promise\Promise(function ($resolve) use ($loop, $stream) {
$loop->addWriteStream($stream, function ($stream) use ($loop, $resolve) {
return new Promise\Promise(function ($resolve, $reject) use ($loop, $stream) {
$loop->addWriteStream($stream, function ($stream) use ($loop, $resolve, $reject) {
$loop->removeWriteStream($stream);

$resolve($stream);
// The following hack looks like the only way to
// detect connection refused errors with PHP's stream sockets.
if (false === stream_socket_get_name($stream, true)) {
fclose($stream);

$reject(new \RuntimeException('Connection refused'));
} else {
$resolve(new Connection($stream, $loop));
}
});
}, function () use ($loop, $stream) {
$loop->removeWriteStream($stream);
Expand All @@ -113,24 +118,4 @@ private function waitForStreamOnce($stream)
throw new \RuntimeException('Cancelled while waiting for TCP/IP connection to be established');
});
}

/** @internal */
public function checkConnectedSocket($socket)
{
// The following hack looks like the only way to
// detect connection refused errors with PHP's stream sockets.
if (false === stream_socket_get_name($socket, true)) {
fclose($socket);

return Promise\reject(new \RuntimeException('Connection refused'));
}

return Promise\resolve($socket);
}

/** @internal */
public function handleConnectedSocket($socket)
{
return new Connection($socket, $this->loop);
}
}

0 comments on commit cefad72

Please sign in to comment.