TcpConnection.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Workerman\Connection;
  15. use Workerman\Events\EventInterface;
  16. use Workerman\Worker;
  17. use Exception;
  18. /**
  19. * TcpConnection.
  20. */
  21. class TcpConnection extends ConnectionInterface
  22. {
  23. /**
  24. * Read buffer size.
  25. *
  26. * @var int
  27. */
  28. const READ_BUFFER_SIZE = 65535;
  29. /**
  30. * Status initial.
  31. *
  32. * @var int
  33. */
  34. const STATUS_INITIAL = 0;
  35. /**
  36. * Status connecting.
  37. *
  38. * @var int
  39. */
  40. const STATUS_CONNECTING = 1;
  41. /**
  42. * Status connection established.
  43. *
  44. * @var int
  45. */
  46. const STATUS_ESTABLISHED = 2;
  47. /**
  48. * Status closing.
  49. *
  50. * @var int
  51. */
  52. const STATUS_CLOSING = 4;
  53. /**
  54. * Status closed.
  55. *
  56. * @var int
  57. */
  58. const STATUS_CLOSED = 8;
  59. /**
  60. * Emitted when data is received.
  61. *
  62. * @var callback
  63. */
  64. public $onMessage = null;
  65. /**
  66. * Emitted when the other end of the socket sends a FIN packet.
  67. *
  68. * @var callback
  69. */
  70. public $onClose = null;
  71. /**
  72. * Emitted when an error occurs with connection.
  73. *
  74. * @var callback
  75. */
  76. public $onError = null;
  77. /**
  78. * Emitted when the send buffer becomes full.
  79. *
  80. * @var callback
  81. */
  82. public $onBufferFull = null;
  83. /**
  84. * Emitted when the send buffer becomes empty.
  85. *
  86. * @var callback
  87. */
  88. public $onBufferDrain = null;
  89. /**
  90. * Application layer protocol.
  91. * The format is like this Workerman\\Protocols\\Http.
  92. *
  93. * @var \Workerman\Protocols\ProtocolInterface
  94. */
  95. public $protocol = null;
  96. /**
  97. * Transport (tcp/udp/unix/ssl).
  98. *
  99. * @var string
  100. */
  101. public $transport = 'tcp';
  102. /**
  103. * Which worker belong to.
  104. *
  105. * @var Worker
  106. */
  107. public $worker = null;
  108. /**
  109. * Bytes read.
  110. *
  111. * @var int
  112. */
  113. public $bytesRead = 0;
  114. /**
  115. * Bytes written.
  116. *
  117. * @var int
  118. */
  119. public $bytesWritten = 0;
  120. /**
  121. * Connection->id.
  122. *
  123. * @var int
  124. */
  125. public $id = 0;
  126. /**
  127. * A copy of $worker->id which used to clean up the connection in worker->connections
  128. *
  129. * @var int
  130. */
  131. protected $_id = 0;
  132. /**
  133. * Sets the maximum send buffer size for the current connection.
  134. * OnBufferFull callback will be emited When the send buffer is full.
  135. *
  136. * @var int
  137. */
  138. public $maxSendBufferSize = 1048576;
  139. /**
  140. * Default send buffer size.
  141. *
  142. * @var int
  143. */
  144. public static $defaultMaxSendBufferSize = 1048576;
  145. /**
  146. * Maximum acceptable packet size.
  147. *
  148. * @var int
  149. */
  150. public static $maxPackageSize = 10485760;
  151. /**
  152. * Id recorder.
  153. *
  154. * @var int
  155. */
  156. protected static $_idRecorder = 1;
  157. /**
  158. * Socket
  159. *
  160. * @var resource
  161. */
  162. protected $_socket = null;
  163. /**
  164. * Send buffer.
  165. *
  166. * @var string
  167. */
  168. protected $_sendBuffer = '';
  169. /**
  170. * Receive buffer.
  171. *
  172. * @var string
  173. */
  174. protected $_recvBuffer = '';
  175. /**
  176. * Current package length.
  177. *
  178. * @var int
  179. */
  180. protected $_currentPackageLength = 0;
  181. /**
  182. * Connection status.
  183. *
  184. * @var int
  185. */
  186. protected $_status = self::STATUS_ESTABLISHED;
  187. /**
  188. * Remote address.
  189. *
  190. * @var string
  191. */
  192. protected $_remoteAddress = '';
  193. /**
  194. * Is paused.
  195. *
  196. * @var bool
  197. */
  198. protected $_isPaused = false;
  199. /**
  200. * SSL handshake completed or not.
  201. *
  202. * @var bool
  203. */
  204. protected $_sslHandshakeCompleted = false;
  205. /**
  206. * All connection instances.
  207. *
  208. * @var array
  209. */
  210. public static $connections = array();
  211. /**
  212. * Status to string.
  213. *
  214. * @var array
  215. */
  216. public static $_statusToString = array(
  217. self::STATUS_INITIAL => 'INITIAL',
  218. self::STATUS_CONNECTING => 'CONNECTING',
  219. self::STATUS_ESTABLISHED => 'ESTABLISHED',
  220. self::STATUS_CLOSING => 'CLOSING',
  221. self::STATUS_CLOSED => 'CLOSED',
  222. );
  223. /**
  224. * Adding support of custom functions within protocols
  225. *
  226. * @param string $name
  227. * @param array $arguments
  228. * @return void
  229. */
  230. public function __call($name, $arguments) {
  231. // Try to emit custom function within protocol
  232. if (method_exists($this->protocol, $name)) {
  233. try {
  234. return call_user_func(array($this->protocol, $name), $this, $arguments);
  235. } catch (\Exception $e) {
  236. Worker::log($e);
  237. exit(250);
  238. } catch (\Error $e) {
  239. Worker::log($e);
  240. exit(250);
  241. }
  242. }
  243. }
  244. /**
  245. * Construct.
  246. *
  247. * @param resource $socket
  248. * @param string $remote_address
  249. */
  250. public function __construct($socket, $remote_address = '')
  251. {
  252. self::$statistics['connection_count']++;
  253. $this->id = $this->_id = self::$_idRecorder++;
  254. if(self::$_idRecorder === PHP_INT_MAX){
  255. self::$_idRecorder = 0;
  256. }
  257. $this->_socket = $socket;
  258. stream_set_blocking($this->_socket, 0);
  259. // Compatible with hhvm
  260. if (function_exists('stream_set_read_buffer')) {
  261. stream_set_read_buffer($this->_socket, 0);
  262. }
  263. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  264. $this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
  265. $this->_remoteAddress = $remote_address;
  266. static::$connections[$this->id] = $this;
  267. }
  268. /**
  269. * Get status.
  270. *
  271. * @param bool $raw_output
  272. *
  273. * @return int
  274. */
  275. public function getStatus($raw_output = true)
  276. {
  277. if ($raw_output) {
  278. return $this->_status;
  279. }
  280. return self::$_statusToString[$this->_status];
  281. }
  282. /**
  283. * Sends data on the connection.
  284. *
  285. * @param string $send_buffer
  286. * @param bool $raw
  287. * @return bool|null
  288. */
  289. public function send($send_buffer, $raw = false)
  290. {
  291. if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
  292. return false;
  293. }
  294. // Try to call protocol::encode($send_buffer) before sending.
  295. if (false === $raw && $this->protocol !== null) {
  296. $parser = $this->protocol;
  297. $send_buffer = $parser::encode($send_buffer, $this);
  298. if ($send_buffer === '') {
  299. return null;
  300. }
  301. }
  302. if ($this->_status !== self::STATUS_ESTABLISHED ||
  303. ($this->transport === 'ssl' && $this->_sslHandshakeCompleted !== true)
  304. ) {
  305. if ($this->_sendBuffer) {
  306. if ($this->bufferIsFull()) {
  307. self::$statistics['send_fail']++;
  308. return false;
  309. }
  310. }
  311. $this->_sendBuffer .= $send_buffer;
  312. $this->checkBufferWillFull();
  313. return null;
  314. }
  315. // Attempt to send data directly.
  316. if ($this->_sendBuffer === '') {
  317. if ($this->transport === 'ssl') {
  318. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  319. $this->_sendBuffer = $send_buffer;
  320. $this->checkBufferWillFull();
  321. return null;
  322. }
  323. set_error_handler(function(){});
  324. $len = fwrite($this->_socket, $send_buffer);
  325. restore_error_handler();
  326. // send successful.
  327. if ($len === strlen($send_buffer)) {
  328. $this->bytesWritten += $len;
  329. return true;
  330. }
  331. // Send only part of the data.
  332. if ($len > 0) {
  333. $this->_sendBuffer = substr($send_buffer, $len);
  334. $this->bytesWritten += $len;
  335. } else {
  336. // Connection closed?
  337. if (!is_resource($this->_socket) || feof($this->_socket)) {
  338. self::$statistics['send_fail']++;
  339. if ($this->onError) {
  340. try {
  341. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'client closed');
  342. } catch (\Exception $e) {
  343. Worker::log($e);
  344. exit(250);
  345. } catch (\Error $e) {
  346. Worker::log($e);
  347. exit(250);
  348. }
  349. }
  350. $this->destroy();
  351. return false;
  352. }
  353. $this->_sendBuffer = $send_buffer;
  354. }
  355. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  356. // Check if the send buffer will be full.
  357. $this->checkBufferWillFull();
  358. return null;
  359. } else {
  360. if ($this->bufferIsFull()) {
  361. self::$statistics['send_fail']++;
  362. return false;
  363. }
  364. $this->_sendBuffer .= $send_buffer;
  365. // Check if the send buffer is full.
  366. $this->checkBufferWillFull();
  367. }
  368. }
  369. /**
  370. * Get remote IP.
  371. *
  372. * @return string
  373. */
  374. public function getRemoteIp()
  375. {
  376. $pos = strrpos($this->_remoteAddress, ':');
  377. if ($pos) {
  378. return substr($this->_remoteAddress, 0, $pos);
  379. }
  380. return '';
  381. }
  382. /**
  383. * Get remote port.
  384. *
  385. * @return int
  386. */
  387. public function getRemotePort()
  388. {
  389. if ($this->_remoteAddress) {
  390. return (int)substr(strrchr($this->_remoteAddress, ':'), 1);
  391. }
  392. return 0;
  393. }
  394. /**
  395. * Get remote address.
  396. *
  397. * @return string
  398. */
  399. public function getRemoteAddress()
  400. {
  401. return $this->_remoteAddress;
  402. }
  403. /**
  404. * Get local IP.
  405. *
  406. * @return string
  407. */
  408. public function getLocalIp()
  409. {
  410. $address = $this->getLocalAddress();
  411. $pos = strrpos($address, ':');
  412. if (!$pos) {
  413. return '';
  414. }
  415. return substr($address, 0, $pos);
  416. }
  417. /**
  418. * Get local port.
  419. *
  420. * @return int
  421. */
  422. public function getLocalPort()
  423. {
  424. $address = $this->getLocalAddress();
  425. $pos = strrpos($address, ':');
  426. if (!$pos) {
  427. return 0;
  428. }
  429. return (int)substr(strrchr($address, ':'), 1);
  430. }
  431. /**
  432. * Get local address.
  433. *
  434. * @return string
  435. */
  436. public function getLocalAddress()
  437. {
  438. return (string)@stream_socket_get_name($this->_socket, false);
  439. }
  440. /**
  441. * Get send buffer queue size.
  442. *
  443. * @return integer
  444. */
  445. public function getSendBufferQueueSize()
  446. {
  447. return strlen($this->_sendBuffer);
  448. }
  449. /**
  450. * Get recv buffer queue size.
  451. *
  452. * @return integer
  453. */
  454. public function getRecvBufferQueueSize()
  455. {
  456. return strlen($this->_recvBuffer);
  457. }
  458. /**
  459. * Is ipv4.
  460. *
  461. * return bool.
  462. */
  463. public function isIpV4()
  464. {
  465. if ($this->transport === 'unix') {
  466. return false;
  467. }
  468. return strpos($this->getRemoteIp(), ':') === false;
  469. }
  470. /**
  471. * Is ipv6.
  472. *
  473. * return bool.
  474. */
  475. public function isIpV6()
  476. {
  477. if ($this->transport === 'unix') {
  478. return false;
  479. }
  480. return strpos($this->getRemoteIp(), ':') !== false;
  481. }
  482. /**
  483. * Pauses the reading of data. That is onMessage will not be emitted. Useful to throttle back an upload.
  484. *
  485. * @return void
  486. */
  487. public function pauseRecv()
  488. {
  489. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  490. $this->_isPaused = true;
  491. }
  492. /**
  493. * Resumes reading after a call to pauseRecv.
  494. *
  495. * @return void
  496. */
  497. public function resumeRecv()
  498. {
  499. if ($this->_isPaused === true) {
  500. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  501. $this->_isPaused = false;
  502. $this->baseRead($this->_socket, false);
  503. }
  504. }
  505. /**
  506. * Base read handler.
  507. *
  508. * @param resource $socket
  509. * @param bool $check_eof
  510. * @return void
  511. */
  512. public function baseRead($socket, $check_eof = true)
  513. {
  514. // SSL handshake.
  515. if ($this->transport === 'ssl' && $this->_sslHandshakeCompleted !== true) {
  516. if ($this->doSslHandshake($socket)) {
  517. $this->_sslHandshakeCompleted = true;
  518. if ($this->_sendBuffer) {
  519. Worker::$globalEvent->add($socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  520. }
  521. } else {
  522. return;
  523. }
  524. }
  525. set_error_handler(function(){});
  526. $buffer = fread($socket, self::READ_BUFFER_SIZE);
  527. restore_error_handler();
  528. // Check connection closed.
  529. if ($buffer === '' || $buffer === false) {
  530. if ($check_eof && (feof($socket) || !is_resource($socket) || $buffer === false)) {
  531. $this->destroy();
  532. return;
  533. }
  534. } else {
  535. $this->bytesRead += strlen($buffer);
  536. $this->_recvBuffer .= $buffer;
  537. }
  538. // If the application layer protocol has been set up.
  539. if ($this->protocol !== null) {
  540. $parser = $this->protocol;
  541. while ($this->_recvBuffer !== '' && !$this->_isPaused) {
  542. // The current packet length is known.
  543. if ($this->_currentPackageLength) {
  544. // Data is not enough for a package.
  545. if ($this->_currentPackageLength > strlen($this->_recvBuffer)) {
  546. break;
  547. }
  548. } else {
  549. // Get current package length.
  550. set_error_handler(function($code, $msg, $file, $line){
  551. Worker::safeEcho("$msg in file $file on line $line\n");
  552. });
  553. $this->_currentPackageLength = $parser::input($this->_recvBuffer, $this);
  554. restore_error_handler();
  555. // The packet length is unknown.
  556. if ($this->_currentPackageLength === 0) {
  557. break;
  558. } elseif ($this->_currentPackageLength > 0 && $this->_currentPackageLength <= static::$maxPackageSize) {
  559. // Data is not enough for a package.
  560. if ($this->_currentPackageLength > strlen($this->_recvBuffer)) {
  561. break;
  562. }
  563. } // Wrong package.
  564. else {
  565. Worker::safeEcho('error package. package_length=' . var_export($this->_currentPackageLength, true));
  566. $this->destroy();
  567. return;
  568. }
  569. }
  570. // The data is enough for a packet.
  571. self::$statistics['total_request']++;
  572. // The current packet length is equal to the length of the buffer.
  573. if (strlen($this->_recvBuffer) === $this->_currentPackageLength) {
  574. $one_request_buffer = $this->_recvBuffer;
  575. $this->_recvBuffer = '';
  576. } else {
  577. // Get a full package from the buffer.
  578. $one_request_buffer = substr($this->_recvBuffer, 0, $this->_currentPackageLength);
  579. // Remove the current package from the receive buffer.
  580. $this->_recvBuffer = substr($this->_recvBuffer, $this->_currentPackageLength);
  581. }
  582. // Reset the current packet length to 0.
  583. $this->_currentPackageLength = 0;
  584. if (!$this->onMessage) {
  585. continue;
  586. }
  587. try {
  588. // Decode request buffer before Emitting onMessage callback.
  589. call_user_func($this->onMessage, $this, $parser::decode($one_request_buffer, $this));
  590. } catch (\Exception $e) {
  591. Worker::log($e);
  592. exit(250);
  593. } catch (\Error $e) {
  594. Worker::log($e);
  595. exit(250);
  596. }
  597. }
  598. return;
  599. }
  600. if ($this->_recvBuffer === '' || $this->_isPaused) {
  601. return;
  602. }
  603. // Applications protocol is not set.
  604. self::$statistics['total_request']++;
  605. if (!$this->onMessage) {
  606. $this->_recvBuffer = '';
  607. return;
  608. }
  609. try {
  610. call_user_func($this->onMessage, $this, $this->_recvBuffer);
  611. } catch (\Exception $e) {
  612. Worker::log($e);
  613. exit(250);
  614. } catch (\Error $e) {
  615. Worker::log($e);
  616. exit(250);
  617. }
  618. // Clean receive buffer.
  619. $this->_recvBuffer = '';
  620. }
  621. /**
  622. * Base write handler.
  623. *
  624. * @return void|bool
  625. */
  626. public function baseWrite()
  627. {
  628. set_error_handler(function(){});
  629. if ($this->transport === 'ssl') {
  630. $len = fwrite($this->_socket, $this->_sendBuffer, 8192);
  631. } else {
  632. $len = fwrite($this->_socket, $this->_sendBuffer);
  633. }
  634. restore_error_handler();
  635. if ($len === strlen($this->_sendBuffer)) {
  636. $this->bytesWritten += $len;
  637. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  638. $this->_sendBuffer = '';
  639. // Try to emit onBufferDrain callback when the send buffer becomes empty.
  640. if ($this->onBufferDrain) {
  641. try {
  642. call_user_func($this->onBufferDrain, $this);
  643. } catch (\Exception $e) {
  644. Worker::log($e);
  645. exit(250);
  646. } catch (\Error $e) {
  647. Worker::log($e);
  648. exit(250);
  649. }
  650. }
  651. if ($this->_status === self::STATUS_CLOSING) {
  652. $this->destroy();
  653. }
  654. return true;
  655. }
  656. if ($len > 0) {
  657. $this->bytesWritten += $len;
  658. $this->_sendBuffer = substr($this->_sendBuffer, $len);
  659. } else {
  660. self::$statistics['send_fail']++;
  661. $this->destroy();
  662. }
  663. }
  664. /**
  665. * SSL handshake.
  666. *
  667. * @param $socket
  668. * @return bool
  669. */
  670. public function doSslHandshake($socket){
  671. if (feof($socket)) {
  672. $this->destroy();
  673. return false;
  674. }
  675. $async = $this instanceof AsyncTcpConnection;
  676. if($async){
  677. $type = STREAM_CRYPTO_METHOD_SSLv2_CLIENT | STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
  678. }else{
  679. $type = STREAM_CRYPTO_METHOD_SSLv2_SERVER | STREAM_CRYPTO_METHOD_SSLv23_SERVER;
  680. }
  681. // Hidden error.
  682. set_error_handler(function($errno, $errstr, $file){
  683. if (!Worker::$daemonize) {
  684. Worker::safeEcho("SSL handshake error: $errstr \n");
  685. }
  686. });
  687. $ret = stream_socket_enable_crypto($socket, true, $type);
  688. restore_error_handler();
  689. // Negotiation has failed.
  690. if (false === $ret) {
  691. $this->destroy();
  692. return false;
  693. } elseif (0 === $ret) {
  694. // There isn't enough data and should try again.
  695. return false;
  696. }
  697. if (isset($this->onSslHandshake)) {
  698. try {
  699. call_user_func($this->onSslHandshake, $this);
  700. } catch (\Exception $e) {
  701. Worker::log($e);
  702. exit(250);
  703. } catch (\Error $e) {
  704. Worker::log($e);
  705. exit(250);
  706. }
  707. }
  708. return true;
  709. }
  710. /**
  711. * This method pulls all the data out of a readable stream, and writes it to the supplied destination.
  712. *
  713. * @param TcpConnection $dest
  714. * @return void
  715. */
  716. public function pipe($dest)
  717. {
  718. $source = $this;
  719. $this->onMessage = function ($source, $data) use ($dest) {
  720. $dest->send($data);
  721. };
  722. $this->onClose = function ($source) use ($dest) {
  723. $dest->destroy();
  724. };
  725. $dest->onBufferFull = function ($dest) use ($source) {
  726. $source->pauseRecv();
  727. };
  728. $dest->onBufferDrain = function ($dest) use ($source) {
  729. $source->resumeRecv();
  730. };
  731. }
  732. /**
  733. * Remove $length of data from receive buffer.
  734. *
  735. * @param int $length
  736. * @return void
  737. */
  738. public function consumeRecvBuffer($length)
  739. {
  740. $this->_recvBuffer = substr($this->_recvBuffer, $length);
  741. }
  742. /**
  743. * Close connection.
  744. *
  745. * @param mixed $data
  746. * @param bool $raw
  747. * @return void
  748. */
  749. public function close($data = null, $raw = false)
  750. {
  751. if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
  752. return;
  753. } else {
  754. if ($data !== null) {
  755. $this->send($data, $raw);
  756. }
  757. $this->_status = self::STATUS_CLOSING;
  758. }
  759. if ($this->_sendBuffer === '') {
  760. $this->destroy();
  761. }
  762. }
  763. /**
  764. * Get the real socket.
  765. *
  766. * @return resource
  767. */
  768. public function getSocket()
  769. {
  770. return $this->_socket;
  771. }
  772. /**
  773. * Check whether the send buffer will be full.
  774. *
  775. * @return void
  776. */
  777. protected function checkBufferWillFull()
  778. {
  779. if ($this->maxSendBufferSize <= strlen($this->_sendBuffer)) {
  780. if ($this->onBufferFull) {
  781. try {
  782. call_user_func($this->onBufferFull, $this);
  783. } catch (\Exception $e) {
  784. Worker::log($e);
  785. exit(250);
  786. } catch (\Error $e) {
  787. Worker::log($e);
  788. exit(250);
  789. }
  790. }
  791. }
  792. }
  793. /**
  794. * Whether send buffer is full.
  795. *
  796. * @return bool
  797. */
  798. protected function bufferIsFull()
  799. {
  800. // Buffer has been marked as full but still has data to send then the packet is discarded.
  801. if ($this->maxSendBufferSize <= strlen($this->_sendBuffer)) {
  802. if ($this->onError) {
  803. try {
  804. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
  805. } catch (\Exception $e) {
  806. Worker::log($e);
  807. exit(250);
  808. } catch (\Error $e) {
  809. Worker::log($e);
  810. exit(250);
  811. }
  812. }
  813. return true;
  814. }
  815. return false;
  816. }
  817. /**
  818. * Whether send buffer is Empty.
  819. *
  820. * @return bool
  821. */
  822. public function bufferIsEmpty()
  823. {
  824. return empty($this->_sendBuffer);
  825. }
  826. /**
  827. * Destroy connection.
  828. *
  829. * @return void
  830. */
  831. public function destroy()
  832. {
  833. // Avoid repeated calls.
  834. if ($this->_status === self::STATUS_CLOSED) {
  835. return;
  836. }
  837. // Remove event listener.
  838. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  839. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  840. // Close socket.
  841. set_error_handler(function(){});
  842. fclose($this->_socket);
  843. restore_error_handler();
  844. $this->_status = self::STATUS_CLOSED;
  845. // Try to emit onClose callback.
  846. if ($this->onClose) {
  847. try {
  848. call_user_func($this->onClose, $this);
  849. } catch (\Exception $e) {
  850. Worker::log($e);
  851. exit(250);
  852. } catch (\Error $e) {
  853. Worker::log($e);
  854. exit(250);
  855. }
  856. }
  857. // Try to emit protocol::onClose
  858. if ($this->protocol && method_exists($this->protocol, 'onClose')) {
  859. try {
  860. call_user_func(array($this->protocol, 'onClose'), $this);
  861. } catch (\Exception $e) {
  862. Worker::log($e);
  863. exit(250);
  864. } catch (\Error $e) {
  865. Worker::log($e);
  866. exit(250);
  867. }
  868. }
  869. if ($this->_status === self::STATUS_CLOSED) {
  870. // Cleaning up the callback to avoid memory leaks.
  871. $this->onMessage = $this->onClose = $this->onError = $this->onBufferFull = $this->onBufferDrain = null;
  872. // Remove from worker->connections.
  873. if ($this->worker) {
  874. unset($this->worker->connections[$this->_id]);
  875. }
  876. unset(static::$connections[$this->_id]);
  877. }
  878. }
  879. /**
  880. * Destruct.
  881. *
  882. * @return void
  883. */
  884. public function __destruct()
  885. {
  886. static $mod;
  887. self::$statistics['connection_count']--;
  888. if (Worker::getGracefulStop()) {
  889. if (!isset($mod)) {
  890. $mod = ceil((self::$statistics['connection_count'] + 1) / 3);
  891. }
  892. if (0 === self::$statistics['connection_count'] % $mod) {
  893. Worker::log('worker[' . posix_getpid() . '] remains ' . self::$statistics['connection_count'] . ' connection(s)');
  894. }
  895. if(0 === self::$statistics['connection_count']) {
  896. Worker::stopAll();
  897. }
  898. }
  899. }
  900. }