TcpConnection.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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. * Tcp连接类
  20. */
  21. class TcpConnection extends ConnectionInterface
  22. {
  23. /**
  24. * 当数据可读时,从socket缓冲区读取多少字节数据
  25. * @var int
  26. */
  27. const READ_BUFFER_SIZE = 65535;
  28. /**
  29. * 连接状态 连接中
  30. * @var int
  31. */
  32. const STATUS_CONNECTING = 1;
  33. /**
  34. * 连接状态 已经建立连接
  35. * @var int
  36. */
  37. const STATUS_ESTABLISH = 2;
  38. /**
  39. * 连接状态 连接关闭中,标识调用了close方法,但是发送缓冲区中任然有数据
  40. * 等待发送缓冲区的数据发送完毕(写入到socket写缓冲区)后执行关闭
  41. * @var int
  42. */
  43. const STATUS_CLOSING = 4;
  44. /**
  45. * 连接状态 已经关闭
  46. * @var int
  47. */
  48. const STATUS_CLOSED = 8;
  49. /**
  50. * 当对端发来数据时,如果设置了$onMessage回调,则执行
  51. * @var callback
  52. */
  53. public $onMessage = null;
  54. /**
  55. * 当连接关闭时,如果设置了$onClose回调,则执行
  56. * @var callback
  57. */
  58. public $onClose = null;
  59. /**
  60. * 当出现错误是,如果设置了$onError回调,则执行
  61. * @var callback
  62. */
  63. public $onError = null;
  64. /**
  65. * 当发送缓冲区满时,如果设置了$onBufferFull回调,则执行
  66. * @var callback
  67. */
  68. public $onBufferFull = null;
  69. /**
  70. * 当发送缓冲区被清空时,如果设置了$onBufferDrain回调,则执行
  71. * @var callback
  72. */
  73. public $onBufferDrain = null;
  74. /**
  75. * 使用的应用层协议,是协议类的名称
  76. * 值类似于 Workerman\\Protocols\\Http
  77. * @var string
  78. */
  79. public $protocol = '';
  80. /**
  81. * 属于哪个worker
  82. * @var Worker
  83. */
  84. public $worker = null;
  85. /**
  86. * 连接的id,一个自增整数
  87. * @var int
  88. */
  89. public $id = 0;
  90. /**
  91. * 连接的id,为$id的副本,用来清理connections中的连接
  92. * @var int
  93. */
  94. protected $_id = 0;
  95. /**
  96. * 设置当前连接的最大发送缓冲区大小,默认大小为TcpConnection::$defaultMaxSendBufferSize
  97. * 当发送缓冲区满时,会尝试触发onBufferFull回调(如果有设置的话)
  98. * 如果没设置onBufferFull回调,由于发送缓冲区满,则后续发送的数据将被丢弃,
  99. * 并触发onError回调,直到发送缓冲区有空位
  100. * 注意 此值可以动态设置
  101. * @var int
  102. */
  103. public $maxSendBufferSize = 1048576;
  104. /**
  105. * 默认发送缓冲区大小,设置此属性会影响所有连接的默认发送缓冲区大小
  106. * 如果想设置某个连接发送缓冲区的大小,可以单独设置对应连接的$maxSendBufferSize属性
  107. * @var int
  108. */
  109. public static $defaultMaxSendBufferSize = 1048576;
  110. /**
  111. * 能接受的最大数据包,为了防止恶意攻击,当数据包的大小大于此值时执行断开
  112. * 注意 此值可以动态设置
  113. * 例如 Workerman\Connection\TcpConnection::$maxPackageSize=1024000;
  114. * @var int
  115. */
  116. public static $maxPackageSize = 10485760;
  117. /**
  118. * id 记录器
  119. * @var int
  120. */
  121. protected static $_idRecorder = 1;
  122. /**
  123. * 实际的socket资源
  124. * @var resource
  125. */
  126. protected $_socket = null;
  127. /**
  128. * 发送缓冲区
  129. * @var string
  130. */
  131. protected $_sendBuffer = '';
  132. /**
  133. * 接收缓冲区
  134. * @var string
  135. */
  136. protected $_recvBuffer = '';
  137. /**
  138. * 当前正在处理的数据包的包长(此值是协议的intput方法的返回值)
  139. * @var int
  140. */
  141. protected $_currentPackageLength = 0;
  142. /**
  143. * 当前的连接状态
  144. * @var int
  145. */
  146. protected $_status = self::STATUS_ESTABLISH;
  147. /**
  148. * 对端的地址 ip+port
  149. * 值类似于 192.168.1.100:3698
  150. * @var string
  151. */
  152. protected $_remoteAddress = '';
  153. /**
  154. * 是否是停止接收数据
  155. * @var bool
  156. */
  157. protected $_isPaused = false;
  158. /**
  159. * 构造函数
  160. * @param resource $socket
  161. * @param EventInterface $event
  162. */
  163. public function __construct($socket, $remote_address = '')
  164. {
  165. // 统计数据
  166. self::$statistics['connection_count']++;
  167. $this->id = $this->_id = self::$_idRecorder++;
  168. $this->_socket = $socket;
  169. stream_set_blocking($this->_socket, 0);
  170. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  171. $this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
  172. $this->_remoteAddress = $remote_address;
  173. }
  174. /**
  175. * 发送数据给对端
  176. * @param string $send_buffer
  177. * @param bool $raw
  178. * @return void|boolean
  179. */
  180. public function send($send_buffer, $raw = false)
  181. {
  182. // 如果没有设置以原始数据发送,并且有设置协议则按照协议编码
  183. if(false === $raw && $this->protocol)
  184. {
  185. $parser = $this->protocol;
  186. $send_buffer = $parser::encode($send_buffer, $this);
  187. if($send_buffer === '')
  188. {
  189. return null;
  190. }
  191. }
  192. // 如果当前状态是连接中,则把数据放入发送缓冲区
  193. if($this->_status === self::STATUS_CONNECTING)
  194. {
  195. $this->_sendBuffer .= $send_buffer;
  196. return null;
  197. }
  198. // 如果当前连接是关闭,则返回false
  199. elseif($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED)
  200. {
  201. return false;
  202. }
  203. // 如果发送缓冲区为空,尝试直接发送
  204. if($this->_sendBuffer === '')
  205. {
  206. // 直接发送
  207. $len = @fwrite($this->_socket, $send_buffer);
  208. // 所有数据都发送完毕
  209. if($len === strlen($send_buffer))
  210. {
  211. return true;
  212. }
  213. // 只有部分数据发送成功
  214. if($len > 0)
  215. {
  216. // 未发送成功部分放入发送缓冲区
  217. $this->_sendBuffer = substr($send_buffer, $len);
  218. }
  219. else
  220. {
  221. // 如果连接断开
  222. if(!is_resource($this->_socket) || feof($this->_socket))
  223. {
  224. // status统计发送失败次数
  225. self::$statistics['send_fail']++;
  226. // 如果有设置失败回调,则执行
  227. if($this->onError)
  228. {
  229. try
  230. {
  231. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'client closed');
  232. }
  233. catch(\Exception $e)
  234. {
  235. echo $e;
  236. exit(250);
  237. }
  238. }
  239. // 销毁连接
  240. $this->destroy();
  241. return false;
  242. }
  243. // 连接未断开,发送失败,则把所有数据放入发送缓冲区
  244. $this->_sendBuffer = $send_buffer;
  245. }
  246. // 监听对端可写事件
  247. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  248. // 检查发送缓冲区是否已满,如果满了尝试触发onBufferFull回调
  249. $this->checkBufferIsFull();
  250. return null;
  251. }
  252. else
  253. {
  254. // 缓冲区已经标记为满,仍然然有数据发送,则丢弃数据包
  255. if($this->maxSendBufferSize <= strlen($this->_sendBuffer))
  256. {
  257. // 为status命令统计发送失败次数
  258. self::$statistics['send_fail']++;
  259. // 如果有设置失败回调,则执行
  260. if($this->onError)
  261. {
  262. try
  263. {
  264. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
  265. }
  266. catch(\Exception $e)
  267. {
  268. echo $e;
  269. exit(250);
  270. }
  271. }
  272. return false;
  273. }
  274. // 将数据放入放缓冲区
  275. $this->_sendBuffer .= $send_buffer;
  276. // 检查发送缓冲区是否已满,如果满了尝试触发onBufferFull回调
  277. $this->checkBufferIsFull();
  278. }
  279. }
  280. /**
  281. * 获得对端ip
  282. * @return string
  283. */
  284. public function getRemoteIp()
  285. {
  286. $pos = strrpos($this->_remoteAddress, ':');
  287. if($pos)
  288. {
  289. return substr($this->_remoteAddress, 0, $pos);
  290. }
  291. return '';
  292. }
  293. /**
  294. * 获得对端端口
  295. * @return int
  296. */
  297. public function getRemotePort()
  298. {
  299. if($this->_remoteAddress)
  300. {
  301. return (int)substr(strrchr($this->_remoteAddress, ':'), 1);
  302. }
  303. return 0;
  304. }
  305. /**
  306. * 暂停接收数据,一般用于控制上传流量
  307. * @return void
  308. */
  309. public function pauseRecv()
  310. {
  311. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  312. $this->_isPaused = true;
  313. }
  314. /**
  315. * 恢复接收数据,一般用户控制上传流量
  316. * @return void
  317. */
  318. public function resumeRecv()
  319. {
  320. if($this->_isPaused === true)
  321. {
  322. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  323. $this->_isPaused = false;
  324. $this->baseRead($this->_socket);
  325. }
  326. }
  327. /**
  328. * 当socket可读时的回调
  329. * @param resource $socket
  330. * @return void
  331. */
  332. public function baseRead($socket)
  333. {
  334. $read_data = false;
  335. while(1)
  336. {
  337. $buffer = fread($socket, self::READ_BUFFER_SIZE);
  338. if($buffer === '' || $buffer === false)
  339. {
  340. break;
  341. }
  342. $read_data = true;
  343. $this->_recvBuffer .= $buffer;
  344. }
  345. // 没有读到数据时检查连接是否断开
  346. if(!$read_data && (!is_resource($socket) || feof($socket)))
  347. {
  348. $this->destroy();
  349. return;
  350. }
  351. // 如果设置了协议
  352. if($this->protocol)
  353. {
  354. $parser = $this->protocol;
  355. while($this->_recvBuffer !== '' && !$this->_isPaused)
  356. {
  357. // 当前包的长度已知
  358. if($this->_currentPackageLength)
  359. {
  360. // 数据不够一个包
  361. if($this->_currentPackageLength > strlen($this->_recvBuffer))
  362. {
  363. break;
  364. }
  365. }
  366. else
  367. {
  368. // 获得当前包长
  369. $this->_currentPackageLength = $parser::input($this->_recvBuffer, $this);
  370. // 数据不够,无法获得包长
  371. if($this->_currentPackageLength === 0)
  372. {
  373. break;
  374. }
  375. elseif($this->_currentPackageLength > 0 && $this->_currentPackageLength <= self::$maxPackageSize)
  376. {
  377. // 数据不够一个包
  378. if($this->_currentPackageLength > strlen($this->_recvBuffer))
  379. {
  380. break;
  381. }
  382. }
  383. // 包错误
  384. else
  385. {
  386. echo 'error package. package_length='.var_export($this->_currentPackageLength, true);
  387. $this->destroy();
  388. return;
  389. }
  390. }
  391. // 数据足够一个包长
  392. self::$statistics['total_request']++;
  393. // 当前包长刚好等于buffer的长度
  394. if(strlen($this->_recvBuffer) === $this->_currentPackageLength)
  395. {
  396. $one_request_buffer = $this->_recvBuffer;
  397. $this->_recvBuffer = '';
  398. }
  399. else
  400. {
  401. // 从缓冲区中获取一个完整的包
  402. $one_request_buffer = substr($this->_recvBuffer, 0, $this->_currentPackageLength);
  403. // 将当前包从接受缓冲区中去掉
  404. $this->_recvBuffer = substr($this->_recvBuffer, $this->_currentPackageLength);
  405. }
  406. // 重置当前包长为0
  407. $this->_currentPackageLength = 0;
  408. if(!$this->onMessage)
  409. {
  410. continue ;
  411. }
  412. try
  413. {
  414. // 处理数据包
  415. call_user_func($this->onMessage, $this, $parser::decode($one_request_buffer, $this));
  416. }
  417. catch(\Exception $e)
  418. {
  419. echo $e;
  420. exit(250);
  421. }
  422. }
  423. return;
  424. }
  425. if($this->_recvBuffer === '' || $this->_isPaused)
  426. {
  427. return;
  428. }
  429. // 没有设置协议,则直接把接收的数据当做一个包处理
  430. self::$statistics['total_request']++;
  431. if(!$this->onMessage)
  432. {
  433. $this->_recvBuffer = '';
  434. return ;
  435. }
  436. try
  437. {
  438. call_user_func($this->onMessage, $this, $this->_recvBuffer);
  439. }
  440. catch(\Exception $e)
  441. {
  442. echo $e;
  443. exit(250);
  444. }
  445. // 清空缓冲区
  446. $this->_recvBuffer = '';
  447. }
  448. /**
  449. * socket可写时的回调
  450. * @return void
  451. */
  452. public function baseWrite()
  453. {
  454. $len = @fwrite($this->_socket, $this->_sendBuffer);
  455. if($len === strlen($this->_sendBuffer))
  456. {
  457. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  458. $this->_sendBuffer = '';
  459. // 发送缓冲区的数据被发送完毕,尝试触发onBufferDrain回调
  460. if($this->onBufferDrain)
  461. {
  462. try
  463. {
  464. call_user_func($this->onBufferDrain, $this);
  465. }
  466. catch(\Exception $e)
  467. {
  468. echo $e;
  469. exit(250);
  470. }
  471. }
  472. // 如果连接状态为关闭,则销毁连接
  473. if($this->_status === self::STATUS_CLOSING)
  474. {
  475. $this->destroy();
  476. }
  477. return true;
  478. }
  479. if($len > 0)
  480. {
  481. $this->_sendBuffer = substr($this->_sendBuffer, $len);
  482. }
  483. // 可写但是写失败,说明连接断开
  484. else
  485. {
  486. self::$statistics['send_fail']++;
  487. $this->destroy();
  488. }
  489. }
  490. /**
  491. * 管道重定向
  492. * @return void
  493. */
  494. public function pipe($dest)
  495. {
  496. $source = $this;
  497. $this->onMessage = function($source, $data)use($dest)
  498. {
  499. $dest->send($data);
  500. };
  501. $this->onClose = function($source)use($dest)
  502. {
  503. $dest->destroy();
  504. };
  505. $dest->onBufferFull = function($dest)use($source)
  506. {
  507. $source->pauseRecv();
  508. };
  509. $dest->onBufferDrain = function($dest)use($source)
  510. {
  511. $source->resumeRecv();
  512. };
  513. }
  514. /**
  515. * 从缓冲区中消费掉$length长度的数据
  516. * @param int $length
  517. * @return void
  518. */
  519. public function consumeRecvBuffer($length)
  520. {
  521. $this->_recvBuffer = substr($this->_recvBuffer, $length);
  522. }
  523. /**
  524. * 关闭连接
  525. * @param mixed $data
  526. * @void
  527. */
  528. public function close($data = null)
  529. {
  530. if($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED)
  531. {
  532. return false;
  533. }
  534. else
  535. {
  536. if($data !== null)
  537. {
  538. $this->send($data);
  539. }
  540. $this->_status = self::STATUS_CLOSING;
  541. }
  542. if($this->_sendBuffer === '')
  543. {
  544. $this->destroy();
  545. }
  546. }
  547. /**
  548. * 获得socket连接
  549. * @return resource
  550. */
  551. public function getSocket()
  552. {
  553. return $this->_socket;
  554. }
  555. /**
  556. * 检查发送缓冲区是否已满,如果满了尝试触发onBufferFull回调
  557. * @return void
  558. */
  559. protected function checkBufferIsFull()
  560. {
  561. if($this->maxSendBufferSize <= strlen($this->_sendBuffer))
  562. {
  563. if($this->onBufferFull)
  564. {
  565. try
  566. {
  567. call_user_func($this->onBufferFull, $this);
  568. }
  569. catch(\Exception $e)
  570. {
  571. echo $e;
  572. exit(250);
  573. }
  574. }
  575. }
  576. }
  577. /**
  578. * 销毁连接
  579. * @return void
  580. */
  581. public function destroy()
  582. {
  583. // 避免重复调用
  584. if($this->_status === self::STATUS_CLOSED)
  585. {
  586. return false;
  587. }
  588. // 删除事件监听
  589. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  590. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  591. // 关闭socket
  592. @fclose($this->_socket);
  593. // 从连接中删除
  594. if($this->worker)
  595. {
  596. unset($this->worker->connections[$this->_id]);
  597. }
  598. // 标记该连接已经关闭
  599. $this->_status = self::STATUS_CLOSED;
  600. // 触发onClose回调
  601. if($this->onClose)
  602. {
  603. try
  604. {
  605. call_user_func($this->onClose, $this);
  606. }
  607. catch(\Exception $e)
  608. {
  609. echo $e;
  610. exit(250);
  611. }
  612. }
  613. // 清理回调,避免内存泄露
  614. $this->onMessage = $this->onClose = $this->onError = $this->onBufferFull = $this->onBufferDrain = null;
  615. }
  616. /**
  617. * 析构函数
  618. * @return void
  619. */
  620. public function __destruct()
  621. {
  622. // 统计数据
  623. self::$statistics['connection_count']--;
  624. }
  625. }