Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions src/Socket.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,16 @@ public function connectTimeout($address, $timeout)
throw $e;
}

// connection should be completed (or rejected) within timeout
if ($this->selectWrite($timeout) === false) {
// connection should be completed (or rejected) within timeout: socket becomes writable on success or error
// Windows requires special care because it uses exceptfds for socket errors: https://github.com/reactphp/event-loop/issues/206
$r = null;
$w = array($this->resource);
$e = DIRECTORY_SEPARATOR === '\\' ? $w : null;
$ret = @socket_select($r, $w, $e, $timeout === null ? null : (int) $timeout, (int) (($timeout - floor($timeout)) * 1000000));

if ($ret === false) {
throw Exception::createFromGlobalSocketOperation('Failed to select socket for writing');
} elseif ($ret === 0) {
throw new Exception('Timed out while waiting for connection', SOCKET_ETIMEDOUT);
}

Expand Down
16 changes: 11 additions & 5 deletions tests/SocketTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,13 @@ public function testConnectAsyncGoogle()

public function testConnectAsyncFailUnbound()
{
if (PHP_OS !== 'Linux') {
$this->markTestSkipped('Only Linux is known to refuse connections to unbound addresses');
$client = @stream_socket_client('localhost:2', $errno, $errstr, 5.0);
if ($client !== false || $errno !== SOCKET_ECONNREFUSED) {
$this->markTestSkipped('Expected unbound address to return ECONNREFUSED, but got errno ' . $errno);
}

if (DIRECTORY_SEPARATOR === '\\') {
$this->markTestIncomplete('Windows uses EWOULDBLOCK and exceptfds, see connectTimeout() instead');
}

$socket = $this->factory->createTcp4();
Expand Down Expand Up @@ -187,15 +192,16 @@ public function testConnectTimeoutFailTimeout()

public function testConnectTimeoutFailUnbound()
{
if (PHP_OS !== 'Linux') {
$this->markTestSkipped('Only Linux is known to refuse connections to unbound addresses');
$client = @stream_socket_client('localhost:2', $errno, $errstr, 5.0);
if ($client !== false || $errno !== SOCKET_ECONNREFUSED) {
$this->markTestSkipped('Expected unbound address to return ECONNREFUSED, but got errno ' . $errno);
}

$socket = $this->factory->createTcp4();

$this->setExpectedException('Socket\Raw\Exception', null, SOCKET_ECONNREFUSED);

$socket->connectTimeout('localhost:2', 0.5);
$socket->connectTimeout('localhost:2', 5.0);
}

/** @group internet */
Expand Down