TcpConnection.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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. * @var int
  26. */
  27. const READ_BUFFER_SIZE = 65535;
  28. /**
  29. * Status connecting.
  30. * @var int
  31. */
  32. const STATUS_CONNECTING = 1;
  33. /**
  34. * Status connection established.
  35. * @var int
  36. */
  37. const STATUS_ESTABLISH = 2;
  38. /**
  39. * Status closing.
  40. * @var int
  41. */
  42. const STATUS_CLOSING = 4;
  43. /**
  44. * Status closed.
  45. * @var int
  46. */
  47. const STATUS_CLOSED = 8;
  48. /**
  49. * Emitted when data is received.
  50. * @var callback
  51. */
  52. public $onMessage = null;
  53. /**
  54. * Emitted when the other end of the socket sends a FIN packet.
  55. * @var callback
  56. */
  57. public $onClose = null;
  58. /**
  59. * Emitted when an error occurs with connection.
  60. * @var callback
  61. */
  62. public $onError = null;
  63. /**
  64. * Emitted when the send buffer becomes full.
  65. * @var callback
  66. */
  67. public $onBufferFull = null;
  68. /**
  69. * Emitted when the send buffer becomes empty.
  70. * @var callback
  71. */
  72. public $onBufferDrain = null;
  73. /**
  74. * Application layer protocol.
  75. * The format is like this Workerman\\Protocols\\Http.
  76. * @var \Workerman\Protocols\ProtocolInterface
  77. */
  78. public $protocol = null;
  79. /**
  80. * Which worker belong to.
  81. * @var Worker
  82. */
  83. public $worker = null;
  84. /**
  85. * Connection->id.
  86. * @var int
  87. */
  88. public $id = 0;
  89. /**
  90. * A copy of $worker->id which used to clean up the connection in worker->connections
  91. * @var int
  92. */
  93. protected $_id = 0;
  94. /**
  95. * Sets the maximum send buffer size for the current connection.
  96. * OnBufferFull callback will be emited When the send buffer is full.
  97. * @var int
  98. */
  99. public $maxSendBufferSize = 1048576;
  100. /**
  101. * Default send buffer size.
  102. * @var int
  103. */
  104. public static $defaultMaxSendBufferSize = 1048576;
  105. /**
  106. * Maximum acceptable packet size.
  107. * @var int
  108. */
  109. public static $maxPackageSize = 10485760;
  110. /**
  111. * Id recorder.
  112. * @var int
  113. */
  114. protected static $_idRecorder = 1;
  115. /**
  116. * Socket
  117. * @var resource
  118. */
  119. protected $_socket = null;
  120. /**
  121. * Send buffer.
  122. * @var string
  123. */
  124. protected $_sendBuffer = '';
  125. /**
  126. * Receive buffer.
  127. * @var string
  128. */
  129. protected $_recvBuffer = '';
  130. /**
  131. * Current package length.
  132. * @var int
  133. */
  134. protected $_currentPackageLength = 0;
  135. /**
  136. * Connection status.
  137. * @var int
  138. */
  139. protected $_status = self::STATUS_ESTABLISH;
  140. /**
  141. * Remote address.
  142. * @var string
  143. */
  144. protected $_remoteAddress = '';
  145. /**
  146. * Is paused.
  147. * @var bool
  148. */
  149. protected $_isPaused = false;
  150. /**
  151. * Construct.
  152. * @param resource $socket
  153. * @param string $remote_address
  154. */
  155. public function __construct($socket, $remote_address = '')
  156. {
  157. self::$statistics['connection_count']++;
  158. $this->id = $this->_id = self::$_idRecorder++;
  159. $this->_socket = $socket;
  160. stream_set_blocking($this->_socket, 0);
  161. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  162. $this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
  163. $this->_remoteAddress = $remote_address;
  164. }
  165. /**
  166. * Sends data on the connection.
  167. * @param string $send_buffer
  168. * @param bool $raw
  169. * @return void|bool|null
  170. */
  171. public function send($send_buffer, $raw = false)
  172. {
  173. // Try to call protocol::encode($send_buffer) before sending.
  174. if(false === $raw && $this->protocol)
  175. {
  176. $parser = $this->protocol;
  177. $send_buffer = $parser::encode($send_buffer, $this);
  178. if($send_buffer === '')
  179. {
  180. return null;
  181. }
  182. }
  183. if($this->_status === self::STATUS_CONNECTING)
  184. {
  185. $this->_sendBuffer .= $send_buffer;
  186. return null;
  187. }
  188. elseif($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED)
  189. {
  190. return false;
  191. }
  192. // Attempt to send data directly.
  193. if($this->_sendBuffer === '')
  194. {
  195. $len = @fwrite($this->_socket, $send_buffer);
  196. // send successful.
  197. if($len === strlen($send_buffer))
  198. {
  199. return true;
  200. }
  201. // Send only part of the data.
  202. if($len > 0)
  203. {
  204. $this->_sendBuffer = substr($send_buffer, $len);
  205. }
  206. else
  207. {
  208. // Connection closed?
  209. if(!is_resource($this->_socket) || feof($this->_socket))
  210. {
  211. self::$statistics['send_fail']++;
  212. if($this->onError)
  213. {
  214. try
  215. {
  216. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'client closed');
  217. }
  218. catch(\Exception $e)
  219. {
  220. echo $e;
  221. exit(250);
  222. }
  223. }
  224. $this->destroy();
  225. return false;
  226. }
  227. $this->_sendBuffer = $send_buffer;
  228. }
  229. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  230. // Check if the send buffer is full.
  231. $this->checkBufferIsFull();
  232. return null;
  233. }
  234. else
  235. {
  236. // Buffer has been marked as full but still has data to send the packet is discarded.
  237. if($this->maxSendBufferSize <= strlen($this->_sendBuffer))
  238. {
  239. self::$statistics['send_fail']++;
  240. if($this->onError)
  241. {
  242. try
  243. {
  244. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
  245. }
  246. catch(\Exception $e)
  247. {
  248. echo $e;
  249. exit(250);
  250. }
  251. }
  252. return false;
  253. }
  254. $this->_sendBuffer .= $send_buffer;
  255. // Check if the send buffer is full.
  256. $this->checkBufferIsFull();
  257. }
  258. }
  259. /**
  260. * Get remote IP.
  261. * @return string
  262. */
  263. public function getRemoteIp()
  264. {
  265. $pos = strrpos($this->_remoteAddress, ':');
  266. if($pos)
  267. {
  268. return substr($this->_remoteAddress, 0, $pos);
  269. }
  270. return '';
  271. }
  272. /**
  273. * Get remote port.
  274. * @return int
  275. */
  276. public function getRemotePort()
  277. {
  278. if($this->_remoteAddress)
  279. {
  280. return (int)substr(strrchr($this->_remoteAddress, ':'), 1);
  281. }
  282. return 0;
  283. }
  284. /**
  285. * Pauses the reading of data. That is onMessage will not be emitted. Useful to throttle back an upload.
  286. * @return void
  287. */
  288. public function pauseRecv()
  289. {
  290. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  291. $this->_isPaused = true;
  292. }
  293. /**
  294. * Resumes reading after a call to pauseRecv.
  295. * @return void
  296. */
  297. public function resumeRecv()
  298. {
  299. if($this->_isPaused === true)
  300. {
  301. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  302. $this->_isPaused = false;
  303. $this->baseRead($this->_socket, false);
  304. }
  305. }
  306. /**
  307. * Base read handler.
  308. * @param resource $socket
  309. * @return void
  310. */
  311. public function baseRead($socket, $check_eof = true)
  312. {
  313. $read_data = false;
  314. while(1)
  315. {
  316. $buffer = fread($socket, self::READ_BUFFER_SIZE);
  317. if($buffer === '' || $buffer === false)
  318. {
  319. break;
  320. }
  321. $read_data = true;
  322. $this->_recvBuffer .= $buffer;
  323. }
  324. // Check connection closed.
  325. if(!$read_data && $check_eof)
  326. {
  327. $this->destroy();
  328. return;
  329. }
  330. // If the application layer protocol has been set up.
  331. if($this->protocol)
  332. {
  333. $parser = $this->protocol;
  334. while($this->_recvBuffer !== '' && !$this->_isPaused)
  335. {
  336. // The current packet length is known.
  337. if($this->_currentPackageLength)
  338. {
  339. // Data is not enough for a package.
  340. if($this->_currentPackageLength > strlen($this->_recvBuffer))
  341. {
  342. break;
  343. }
  344. }
  345. else
  346. {
  347. // Get current package length.
  348. $this->_currentPackageLength = $parser::input($this->_recvBuffer, $this);
  349. // The packet length is unknown.
  350. if($this->_currentPackageLength === 0)
  351. {
  352. break;
  353. }
  354. elseif($this->_currentPackageLength > 0 && $this->_currentPackageLength <= self::$maxPackageSize)
  355. {
  356. // Data is not enough for a package.
  357. if($this->_currentPackageLength > strlen($this->_recvBuffer))
  358. {
  359. break;
  360. }
  361. }
  362. // Wrong package.
  363. else
  364. {
  365. echo 'error package. package_length='.var_export($this->_currentPackageLength, true);
  366. $this->destroy();
  367. return;
  368. }
  369. }
  370. // The data is enough for a packet.
  371. self::$statistics['total_request']++;
  372. // The current packet length is equal to the length of the buffer.
  373. if(strlen($this->_recvBuffer) === $this->_currentPackageLength)
  374. {
  375. $one_request_buffer = $this->_recvBuffer;
  376. $this->_recvBuffer = '';
  377. }
  378. else
  379. {
  380. // Get a full package from the buffer.
  381. $one_request_buffer = substr($this->_recvBuffer, 0, $this->_currentPackageLength);
  382. // Remove the current package from the receive buffer.
  383. $this->_recvBuffer = substr($this->_recvBuffer, $this->_currentPackageLength);
  384. }
  385. // Reset the current packet length to 0.
  386. $this->_currentPackageLength = 0;
  387. if(!$this->onMessage)
  388. {
  389. continue ;
  390. }
  391. try
  392. {
  393. // Decode request buffer before Emiting onMessage callback.
  394. call_user_func($this->onMessage, $this, $parser::decode($one_request_buffer, $this));
  395. }
  396. catch(\Exception $e)
  397. {
  398. echo $e;
  399. exit(250);
  400. }
  401. }
  402. return;
  403. }
  404. if($this->_recvBuffer === '' || $this->_isPaused)
  405. {
  406. return;
  407. }
  408. // Applications protocol is not set.
  409. self::$statistics['total_request']++;
  410. if(!$this->onMessage)
  411. {
  412. $this->_recvBuffer = '';
  413. return ;
  414. }
  415. try
  416. {
  417. call_user_func($this->onMessage, $this, $this->_recvBuffer);
  418. }
  419. catch(\Exception $e)
  420. {
  421. echo $e;
  422. exit(250);
  423. }
  424. // Clean receive buffer.
  425. $this->_recvBuffer = '';
  426. }
  427. /**
  428. * Base write handler.
  429. * @return void|bool
  430. */
  431. public function baseWrite()
  432. {
  433. $len = @fwrite($this->_socket, $this->_sendBuffer);
  434. if($len === strlen($this->_sendBuffer))
  435. {
  436. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  437. $this->_sendBuffer = '';
  438. // Try to emit onBufferDrain callback when the send buffer becomes empty.
  439. if($this->onBufferDrain)
  440. {
  441. try
  442. {
  443. call_user_func($this->onBufferDrain, $this);
  444. }
  445. catch(\Exception $e)
  446. {
  447. echo $e;
  448. exit(250);
  449. }
  450. }
  451. if($this->_status === self::STATUS_CLOSING)
  452. {
  453. $this->destroy();
  454. }
  455. return true;
  456. }
  457. if($len > 0)
  458. {
  459. $this->_sendBuffer = substr($this->_sendBuffer, $len);
  460. }
  461. else
  462. {
  463. self::$statistics['send_fail']++;
  464. $this->destroy();
  465. }
  466. }
  467. /**
  468. * This method pulls all the data out of a readable stream, and writes it to the supplied destination.
  469. * @param TcpConnection $dest
  470. * @return void
  471. */
  472. public function pipe($dest)
  473. {
  474. $source = $this;
  475. $this->onMessage = function($source, $data)use($dest)
  476. {
  477. $dest->send($data);
  478. };
  479. $this->onClose = function($source)use($dest)
  480. {
  481. $dest->destroy();
  482. };
  483. $dest->onBufferFull = function($dest)use($source)
  484. {
  485. $source->pauseRecv();
  486. };
  487. $dest->onBufferDrain = function($dest)use($source)
  488. {
  489. $source->resumeRecv();
  490. };
  491. }
  492. /**
  493. * Remove $length of data from receive buffer.
  494. * @param int $length
  495. * @return void
  496. */
  497. public function consumeRecvBuffer($length)
  498. {
  499. $this->_recvBuffer = substr($this->_recvBuffer, $length);
  500. }
  501. /**
  502. * Close connection.
  503. * @param mixed $data
  504. * @return void
  505. */
  506. public function close($data = null)
  507. {
  508. if($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED)
  509. {
  510. return;
  511. }
  512. else
  513. {
  514. if($data !== null)
  515. {
  516. $this->send($data);
  517. }
  518. $this->_status = self::STATUS_CLOSING;
  519. }
  520. if($this->_sendBuffer === '')
  521. {
  522. $this->destroy();
  523. }
  524. }
  525. /**
  526. * Get the real socket.
  527. * @return resource
  528. */
  529. public function getSocket()
  530. {
  531. return $this->_socket;
  532. }
  533. /**
  534. * Check whether the send buffer is full.
  535. * @return void
  536. */
  537. protected function checkBufferIsFull()
  538. {
  539. if($this->maxSendBufferSize <= strlen($this->_sendBuffer))
  540. {
  541. if($this->onBufferFull)
  542. {
  543. try
  544. {
  545. call_user_func($this->onBufferFull, $this);
  546. }
  547. catch(\Exception $e)
  548. {
  549. echo $e;
  550. exit(250);
  551. }
  552. }
  553. }
  554. }
  555. /**
  556. * Destroy connection.
  557. * @return void
  558. */
  559. public function destroy()
  560. {
  561. // Avoid repeated calls.
  562. if($this->_status === self::STATUS_CLOSED)
  563. {
  564. return;
  565. }
  566. // Remove event listener.
  567. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  568. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  569. // Close socket.
  570. @fclose($this->_socket);
  571. // Remove from worker->connections.
  572. if($this->worker)
  573. {
  574. unset($this->worker->connections[$this->_id]);
  575. }
  576. $this->_status = self::STATUS_CLOSED;
  577. // Try to emit onClose callback.
  578. if($this->onClose)
  579. {
  580. try
  581. {
  582. call_user_func($this->onClose, $this);
  583. }
  584. catch(\Exception $e)
  585. {
  586. echo $e;
  587. exit(250);
  588. }
  589. }
  590. // Cleaning up the callback to avoid memory leaks.
  591. $this->onMessage = $this->onClose = $this->onError = $this->onBufferFull = $this->onBufferDrain = null;
  592. }
  593. /**
  594. * Destruct.
  595. * @return void
  596. */
  597. public function __destruct()
  598. {
  599. self::$statistics['connection_count']--;
  600. }
  601. }