Skip to content

Commit

Permalink
Merge pull request #68 from clue-labs/select-null
Browse files Browse the repository at this point in the history
Fix strict types for `socket_select()` without timeout on PHP 8+
  • Loading branch information
SimonFrings authored Apr 5, 2022
2 parents 5ed4f15 + f951acc commit 4deae62
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/Socket.php
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ public function recvFrom($length, $flags, &$remote)
*/
public function selectRead($sec = 0)
{
$usec = $sec === null ? null : (int) (($sec - floor($sec)) * 1000000);
$usec = $sec === null ? 0 : (int) (($sec - floor($sec)) * 1000000);
$r = array($this->resource);
$n = null;
$ret = @socket_select($r, $n, $n, $sec === null ? null : (int) $sec, $usec);
Expand All @@ -334,7 +334,7 @@ public function selectRead($sec = 0)
*/
public function selectWrite($sec = 0)
{
$usec = $sec === null ? null : (int) (($sec - floor($sec)) * 1000000);
$usec = $sec === null ? 0 : (int) (($sec - floor($sec)) * 1000000);
$w = array($this->resource);
$n = null;
$ret = @socket_select($n, $w, $n, $sec === null ? null : (int) $sec, $usec);
Expand Down
38 changes: 37 additions & 1 deletion tests/SocketTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -254,12 +254,48 @@ public function testServerNonBlockingAcceptClient(Socket $server)
// disconnect local client
$client->close();

// disconnection should be detected withing 1s max
// disconnection should be detected within 1s max
$this->assertTrue($peer->selectRead(1.0));

$peer->close();
}

/**
* @depends testServerNonBlockingAcceptClient
*/
public function testServerAcceptsClientWithoutTimeout()
{
$server = $this->factory->createListen(0);

// create local client connected to the given server
$client = $this->factory->createClient($server->getSockName());

// client connected, so we should be able to accept() this socket immediately
$now = microtime(true);
$server->selectRead(null);
$peer = $server->accept();
$this->assertLessThan(1.0, microtime(true) - $now);

// peer should be writable right away
$now = microtime(true);
$this->assertTrue($peer->selectWrite(null));
$peer->write('test');
$this->assertLessThan(1.0, microtime(true) - $now);

// expect to receive the message in one chunk
$this->assertEquals('test', $client->read(100));

// disconnect local client
$client->close();

// disconnection should be detected within 1s max
$now = microtime(true);
$this->assertTrue($peer->selectRead(null));
$this->assertLessThan(1.0, microtime(true) - $now);

$peer->close();
}

public function testBindThrowsWhenSocketIsAlreadyClosed()
{
$socket = $this->factory->createTcp4();
Expand Down

0 comments on commit 4deae62

Please sign in to comment.