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