Skip to content

Commit 3fab905

Browse files
authored
Merge pull request #244 from clue-labs/accept-race
Fix possible `accept()` race condition when multiple socket servers listen on same socket address
2 parents ce608c8 + 3cb0ddd commit 3fab905

File tree

4 files changed

+12
-4
lines changed

4 files changed

+12
-4
lines changed

src/TcpServer.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ public function resume()
204204

205205
$that = $this;
206206
$this->loop->addReadStream($this->master, function ($master) use ($that) {
207-
$newSocket = @\stream_socket_accept($master);
207+
$newSocket = @\stream_socket_accept($master, 0);
208208
if (false === $newSocket) {
209209
$that->emit('error', array(new \RuntimeException('Error accepting new connection')));
210210

src/UnixServer.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ public function resume()
106106

107107
$that = $this;
108108
$this->loop->addReadStream($this->master, function ($master) use ($that) {
109-
$newSocket = @\stream_socket_accept($master);
109+
$newSocket = @\stream_socket_accept($master, 0);
110110
if (false === $newSocket) {
111111
$that->emit('error', array(new \RuntimeException('Error accepting new connection')));
112112

tests/TcpServerTest.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -280,8 +280,12 @@ public function testEmitsErrorWhenAcceptListenerFails()
280280

281281
$this->assertNotNull($listener);
282282
$socket = stream_socket_server('tcp://127.0.0.1:0');
283-
fclose($socket);
283+
284+
$time = microtime(true);
284285
$listener($socket);
286+
$time = microtime(true) - $time;
287+
288+
$this->assertLessThan(1, $time);
285289
}
286290

287291
public function testListenOnBusyPortThrows()

tests/UnixServerTest.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -285,8 +285,12 @@ public function testEmitsErrorWhenAcceptListenerFails()
285285

286286
$this->assertNotNull($listener);
287287
$socket = stream_socket_server('tcp://127.0.0.1:0');
288-
fclose($socket);
288+
289+
$time = microtime(true);
289290
$listener($socket);
291+
$time = microtime(true) - $time;
292+
293+
$this->assertLessThan(1, $time);
290294
}
291295

292296
public function testListenOnBusyPortThrows()

0 commit comments

Comments
 (0)