TcpServerTest.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. <?php
  2. namespace React\Tests\Socket;
  3. use React\EventLoop\Loop;
  4. use React\Socket\TcpServer;
  5. use React\Stream\DuplexResourceStream;
  6. use React\Promise\Promise;
  7. class TcpServerTest extends TestCase
  8. {
  9. const TIMEOUT = 5.0;
  10. private $server;
  11. private $port;
  12. /**
  13. * @before
  14. * @covers React\Socket\TcpServer::__construct
  15. * @covers React\Socket\TcpServer::getAddress
  16. */
  17. public function setUpServer()
  18. {
  19. $this->server = new TcpServer(0);
  20. $this->port = parse_url($this->server->getAddress(), PHP_URL_PORT);
  21. }
  22. public function testConstructWithoutLoopAssignsLoopAutomatically()
  23. {
  24. $server = new TcpServer(0);
  25. $ref = new \ReflectionProperty($server, 'loop');
  26. $ref->setAccessible(true);
  27. $loop = $ref->getValue($server);
  28. $this->assertInstanceOf('React\EventLoop\LoopInterface', $loop);
  29. $server->close();
  30. }
  31. /**
  32. * @covers React\Socket\TcpServer::handleConnection
  33. */
  34. public function testServerEmitsConnectionEventForNewConnection()
  35. {
  36. $client = stream_socket_client('tcp://localhost:'.$this->port);
  37. assert($client !== false);
  38. $server = $this->server;
  39. $promise = new Promise(function ($resolve) use ($server) {
  40. $server->on('connection', $resolve);
  41. });
  42. $connection = \React\Async\await(\React\Promise\Timer\timeout($promise, self::TIMEOUT));
  43. $this->assertInstanceOf('React\Socket\ConnectionInterface', $connection);
  44. }
  45. /**
  46. * @covers React\Socket\TcpServer::handleConnection
  47. */
  48. public function testConnectionWithManyClients()
  49. {
  50. $client1 = stream_socket_client('tcp://localhost:'.$this->port);
  51. $client2 = stream_socket_client('tcp://localhost:'.$this->port);
  52. $client3 = stream_socket_client('tcp://localhost:'.$this->port);
  53. assert($client1 !== false && $client2 !== false && $client3 !== false);
  54. $this->server->on('connection', $this->expectCallableExactly(3));
  55. $this->tick();
  56. $this->tick();
  57. $this->tick();
  58. $this->tick();
  59. }
  60. public function testDataEventWillNotBeEmittedWhenClientSendsNoData()
  61. {
  62. $client = stream_socket_client('tcp://localhost:'.$this->port);
  63. assert($client !== false);
  64. $mock = $this->expectCallableNever();
  65. $this->server->on('connection', function ($conn) use ($mock) {
  66. $conn->on('data', $mock);
  67. });
  68. $this->tick();
  69. $this->tick();
  70. }
  71. public function testDataWillBeEmittedWithDataClientSends()
  72. {
  73. $client = stream_socket_client('tcp://localhost:'.$this->port);
  74. fwrite($client, "foo\n");
  75. $mock = $this->expectCallableOnceWith("foo\n");
  76. $this->server->on('connection', function ($conn) use ($mock) {
  77. $conn->on('data', $mock);
  78. });
  79. $this->tick();
  80. $this->tick();
  81. }
  82. public function testDataWillBeEmittedEvenWhenClientShutsDownAfterSending()
  83. {
  84. $client = stream_socket_client('tcp://localhost:' . $this->port);
  85. fwrite($client, "foo\n");
  86. stream_socket_shutdown($client, STREAM_SHUT_WR);
  87. $mock = $this->expectCallableOnceWith("foo\n");
  88. $this->server->on('connection', function ($conn) use ($mock) {
  89. $conn->on('data', $mock);
  90. });
  91. $this->tick();
  92. $this->tick();
  93. }
  94. public function testLoopWillEndWhenServerIsClosed()
  95. {
  96. // explicitly unset server because we already call close()
  97. $this->server->close();
  98. $this->server = null;
  99. Loop::run();
  100. // if we reach this, then everything is good
  101. $this->assertNull(null);
  102. }
  103. public function testCloseTwiceIsNoOp()
  104. {
  105. $this->server->close();
  106. $this->server->close();
  107. // if we reach this, then everything is good
  108. $this->assertNull(null);
  109. }
  110. public function testGetAddressAfterCloseReturnsNull()
  111. {
  112. $this->server->close();
  113. $this->assertNull($this->server->getAddress());
  114. }
  115. public function testLoopWillEndWhenServerIsClosedAfterSingleConnection()
  116. {
  117. $client = stream_socket_client('tcp://localhost:' . $this->port);
  118. assert($client !== false);
  119. // explicitly unset server because we only accept a single connection
  120. // and then already call close()
  121. $server = $this->server;
  122. $this->server = null;
  123. $server->on('connection', function ($conn) use ($server) {
  124. $conn->close();
  125. $server->close();
  126. });
  127. Loop::run();
  128. // if we reach this, then everything is good
  129. $this->assertNull(null);
  130. }
  131. public function testDataWillBeEmittedInMultipleChunksWhenClientSendsExcessiveAmounts()
  132. {
  133. $client = stream_socket_client('tcp://localhost:' . $this->port);
  134. $stream = new DuplexResourceStream($client);
  135. $bytes = 1024 * 1024;
  136. $stream->end(str_repeat('*', $bytes));
  137. $mock = $this->expectCallableOnce();
  138. // explicitly unset server because we only accept a single connection
  139. // and then already call close()
  140. $server = $this->server;
  141. $this->server = null;
  142. $received = 0;
  143. $server->on('connection', function ($conn) use ($mock, &$received, $server) {
  144. // count number of bytes received
  145. $conn->on('data', function ($data) use (&$received) {
  146. $received += strlen($data);
  147. });
  148. $conn->on('end', $mock);
  149. // do not await any further connections in order to let the loop terminate
  150. $server->close();
  151. });
  152. Loop::run();
  153. $this->assertEquals($bytes, $received);
  154. }
  155. public function testConnectionDoesNotEndWhenClientDoesNotClose()
  156. {
  157. $client = stream_socket_client('tcp://localhost:'.$this->port);
  158. assert($client !== false);
  159. $mock = $this->expectCallableNever();
  160. $this->server->on('connection', function ($conn) use ($mock) {
  161. $conn->on('end', $mock);
  162. });
  163. $this->tick();
  164. $this->tick();
  165. }
  166. /**
  167. * @covers React\Socket\Connection::end
  168. */
  169. public function testConnectionDoesEndWhenClientCloses()
  170. {
  171. $client = stream_socket_client('tcp://localhost:'.$this->port);
  172. fclose($client);
  173. $mock = $this->expectCallableOnce();
  174. $this->server->on('connection', function ($conn) use ($mock) {
  175. $conn->on('end', $mock);
  176. });
  177. $this->tick();
  178. $this->tick();
  179. }
  180. public function testCtorAddsResourceToLoop()
  181. {
  182. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  183. $loop->expects($this->once())->method('addReadStream');
  184. new TcpServer(0, $loop);
  185. }
  186. public function testResumeWithoutPauseIsNoOp()
  187. {
  188. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  189. $loop->expects($this->once())->method('addReadStream');
  190. $server = new TcpServer(0, $loop);
  191. $server->resume();
  192. }
  193. public function testPauseRemovesResourceFromLoop()
  194. {
  195. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  196. $loop->expects($this->once())->method('removeReadStream');
  197. $server = new TcpServer(0, $loop);
  198. $server->pause();
  199. }
  200. public function testPauseAfterPauseIsNoOp()
  201. {
  202. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  203. $loop->expects($this->once())->method('removeReadStream');
  204. $server = new TcpServer(0, $loop);
  205. $server->pause();
  206. $server->pause();
  207. }
  208. public function testCloseRemovesResourceFromLoop()
  209. {
  210. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  211. $loop->expects($this->once())->method('removeReadStream');
  212. $server = new TcpServer(0, $loop);
  213. $server->close();
  214. }
  215. public function testEmitsErrorWhenAcceptListenerFailsWithoutCallingCustomErrorHandler()
  216. {
  217. $listener = null;
  218. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  219. $loop->expects($this->once())->method('addReadStream')->with($this->anything(), $this->callback(function ($cb) use (&$listener) {
  220. $listener = $cb;
  221. return true;
  222. }));
  223. $server = new TcpServer(0, $loop);
  224. $exception = null;
  225. $server->on('error', function ($e) use (&$exception) {
  226. $exception = $e;
  227. });
  228. $this->assertNotNull($listener);
  229. $socket = stream_socket_server('tcp://127.0.0.1:0');
  230. $error = null;
  231. set_error_handler(function ($_, $errstr) use (&$error) {
  232. $error = $errstr;
  233. });
  234. $time = microtime(true);
  235. $listener($socket);
  236. $time = microtime(true) - $time;
  237. restore_error_handler();
  238. $this->assertNull($error);
  239. $this->assertLessThan(1, $time);
  240. $this->assertInstanceOf('RuntimeException', $exception);
  241. assert($exception instanceof \RuntimeException);
  242. $this->assertStringStartsWith('Unable to accept new connection: ', $exception->getMessage());
  243. return $exception;
  244. }
  245. /**
  246. * @param \RuntimeException $e
  247. * @requires extension sockets
  248. * @depends testEmitsErrorWhenAcceptListenerFailsWithoutCallingCustomErrorHandler
  249. */
  250. public function testEmitsTimeoutErrorWhenAcceptListenerFails(\RuntimeException $exception)
  251. {
  252. if (defined('HHVM_VERSION')) {
  253. $this->markTestSkipped('Not supported on HHVM');
  254. }
  255. $this->assertEquals('Unable to accept new connection: ' . socket_strerror(SOCKET_ETIMEDOUT) . ' (ETIMEDOUT)', $exception->getMessage());
  256. $this->assertEquals(SOCKET_ETIMEDOUT, $exception->getCode());
  257. }
  258. public function testListenOnBusyPortThrows()
  259. {
  260. if (DIRECTORY_SEPARATOR === '\\') {
  261. $this->markTestSkipped('Windows supports listening on same port multiple times');
  262. }
  263. if (defined('HHVM_VERSION')) {
  264. $this->markTestSkipped('Not supported on HHVM');
  265. }
  266. $this->setExpectedException(
  267. 'RuntimeException',
  268. 'Failed to listen on "tcp://127.0.0.1:' . $this->port . '": ' . (function_exists('socket_strerror') ? socket_strerror(SOCKET_EADDRINUSE) . ' (EADDRINUSE)' : 'Address already in use'),
  269. defined('SOCKET_EADDRINUSE') ? SOCKET_EADDRINUSE : 0
  270. );
  271. new TcpServer($this->port);
  272. }
  273. /**
  274. * @after
  275. * @covers React\Socket\TcpServer::close
  276. */
  277. public function tearDownServer()
  278. {
  279. if ($this->server) {
  280. $this->server->close();
  281. }
  282. }
  283. /**
  284. * This methods runs the loop for "one tick"
  285. *
  286. * This is prone to race conditions and as such somewhat unreliable across
  287. * different operating systems. Running the loop until the expected events
  288. * fire is the preferred alternative.
  289. *
  290. * @deprecated
  291. */
  292. private function tick()
  293. {
  294. if (DIRECTORY_SEPARATOR === '\\') {
  295. $this->markTestSkipped('Not supported on Windows');
  296. }
  297. \React\Async\await(\React\Promise\Timer\sleep(0.0));
  298. }
  299. }