TcpConnection.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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. }
  194. // 如果当前状态是连接中,则把数据放入发送缓冲区
  195. if($this->_status === self::STATUS_CONNECTING)
  196. {
  197. $this->_sendBuffer .= $send_buffer;
  198. return null;
  199. }
  200. // 如果当前连接是关闭,则返回false
  201. elseif($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED)
  202. {
  203. return false;
  204. }
  205. // 如果发送缓冲区为空,尝试直接发送
  206. if($this->_sendBuffer === '')
  207. {
  208. // 直接发送
  209. $len = @fwrite($this->_socket, $send_buffer);
  210. // 所有数据都发送完毕
  211. if($len === strlen($send_buffer))
  212. {
  213. return true;
  214. }
  215. // 只有部分数据发送成功
  216. if($len > 0)
  217. {
  218. // 未发送成功部分放入发送缓冲区
  219. $this->_sendBuffer = substr($send_buffer, $len);
  220. }
  221. else
  222. {
  223. // 如果连接断开
  224. if(feof($this->_socket))
  225. {
  226. // status统计发送失败次数
  227. self::$statistics['send_fail']++;
  228. // 如果有设置失败回调,则执行
  229. if($this->onError)
  230. {
  231. try
  232. {
  233. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'client closed');
  234. }
  235. catch(Exception $e)
  236. {
  237. echo $e;
  238. }
  239. }
  240. // 销毁连接
  241. $this->destroy();
  242. return false;
  243. }
  244. // 连接未断开,发送失败,则把所有数据放入发送缓冲区
  245. $this->_sendBuffer = $send_buffer;
  246. }
  247. // 监听对端可写事件
  248. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  249. // 检查发送缓冲区是否已满,如果满了尝试触发onBufferFull回调
  250. $this->checkBufferIsFull();
  251. return null;
  252. }
  253. else
  254. {
  255. // 缓冲区已经标记为满,仍然然有数据发送,则丢弃数据包
  256. if($this->maxSendBufferSize <= strlen($this->_sendBuffer))
  257. {
  258. // 为status命令统计发送失败次数
  259. self::$statistics['send_fail']++;
  260. // 如果有设置失败回调,则执行
  261. if($this->onError)
  262. {
  263. try
  264. {
  265. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
  266. }
  267. catch(Exception $e)
  268. {
  269. echo $e;
  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. if(!$this->_remoteIp)
  287. {
  288. $this->_remoteAddress = stream_socket_get_name($this->_socket, true);
  289. if($this->_remoteAddress)
  290. {
  291. list($this->_remoteIp, $this->_remotePort) = explode(':', $this->_remoteAddress, 2);
  292. $this->_remotePort = (int)$this->_remotePort;
  293. }
  294. }
  295. return $this->_remoteIp;
  296. }
  297. /**
  298. * 获得对端端口
  299. * @return int
  300. */
  301. public function getRemotePort()
  302. {
  303. if(!$this->_remotePort)
  304. {
  305. $this->_remoteAddress = stream_socket_get_name($this->_socket, true);
  306. if($this->_remoteAddress)
  307. {
  308. list($this->_remoteIp, $this->_remotePort) = explode(':', $this->_remoteAddress, 2);
  309. $this->_remotePort = (int)$this->_remotePort;
  310. }
  311. }
  312. return $this->_remotePort;
  313. }
  314. /**
  315. * 暂停接收数据,一般用于控制上传流量
  316. * @return void
  317. */
  318. public function pauseRecv()
  319. {
  320. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  321. $this->_isPaused = true;
  322. }
  323. /**
  324. * 恢复接收数据,一般用户控制上传流量
  325. * @return void
  326. */
  327. public function resumeRecv()
  328. {
  329. if($this->_isPaused === true)
  330. {
  331. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  332. $this->_isPaused = false;
  333. $this->baseRead($this->_socket);
  334. }
  335. }
  336. /**
  337. * 当socket可读时的回调
  338. * @param resource $socket
  339. * @return void
  340. */
  341. public function baseRead($socket)
  342. {
  343. if(!is_resource($socket) || feof($socket))
  344. {
  345. $this->destroy();
  346. return;
  347. }
  348. while(1)
  349. {
  350. $buffer = fread($socket, self::READ_BUFFER_SIZE);
  351. if($buffer === '' || $buffer === false)
  352. {
  353. break;
  354. }
  355. $this->_recvBuffer .= $buffer;
  356. }
  357. if($this->_recvBuffer)
  358. {
  359. if(!$this->onMessage)
  360. {
  361. $this->_recvBuffer = '';
  362. return ;
  363. }
  364. // 如果设置了协议
  365. if($this->protocol)
  366. {
  367. $parser = $this->protocol;
  368. while($this->_recvBuffer && !$this->_isPaused)
  369. {
  370. // 当前包的长度已知
  371. if($this->_currentPackageLength)
  372. {
  373. // 数据不够一个包
  374. if($this->_currentPackageLength > strlen($this->_recvBuffer))
  375. {
  376. break;
  377. }
  378. }
  379. else
  380. {
  381. // 获得当前包长
  382. $this->_currentPackageLength = $parser::input($this->_recvBuffer, $this);
  383. // 数据不够,无法获得包长
  384. if($this->_currentPackageLength === 0)
  385. {
  386. break;
  387. }
  388. elseif($this->_currentPackageLength > 0 && $this->_currentPackageLength <= self::$maxPackageSize)
  389. {
  390. // 数据不够一个包
  391. if($this->_currentPackageLength > strlen($this->_recvBuffer))
  392. {
  393. break;
  394. }
  395. }
  396. // 包错误
  397. else
  398. {
  399. $this->close('error package. package_length='.var_export($this->_currentPackageLength, true));
  400. return;
  401. }
  402. }
  403. // 数据足够一个包长
  404. self::$statistics['total_request']++;
  405. // 当前包长刚好等于buffer的长度
  406. if(strlen($this->_recvBuffer) === $this->_currentPackageLength)
  407. {
  408. $one_request_buffer = $this->_recvBuffer;
  409. $this->_recvBuffer = '';
  410. }
  411. else
  412. {
  413. // 从缓冲区中获取一个完整的包
  414. $one_request_buffer = substr($this->_recvBuffer, 0, $this->_currentPackageLength);
  415. // 将当前包从接受缓冲区中去掉
  416. $this->_recvBuffer = substr($this->_recvBuffer, $this->_currentPackageLength);
  417. }
  418. // 重置当前包长为0
  419. $this->_currentPackageLength = 0;
  420. // 处理数据包
  421. try
  422. {
  423. call_user_func($this->onMessage, $this, $parser::decode($one_request_buffer, $this));
  424. }
  425. catch(Exception $e)
  426. {
  427. self::$statistics['throw_exception']++;
  428. echo $e;
  429. }
  430. }
  431. return;
  432. }
  433. // 没有设置协议,则直接把接收的数据当做一个包处理
  434. self::$statistics['total_request']++;
  435. try
  436. {
  437. call_user_func($this->onMessage, $this, $this->_recvBuffer);
  438. }
  439. catch(Exception $e)
  440. {
  441. self::$statistics['throw_exception']++;
  442. echo $e;
  443. }
  444. // 清空缓冲区
  445. $this->_recvBuffer = '';
  446. }
  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. }
  470. }
  471. // 如果连接状态为关闭,则销毁连接
  472. if($this->_status === self::STATUS_CLOSING)
  473. {
  474. $this->destroy();
  475. }
  476. return true;
  477. }
  478. if($len > 0)
  479. {
  480. $this->_sendBuffer = substr($this->_sendBuffer, $len);
  481. }
  482. else
  483. {
  484. if(feof($this->_socket))
  485. {
  486. self::$statistics['send_fail']++;
  487. $this->destroy();
  488. }
  489. }
  490. }
  491. /**
  492. * 从缓冲区中消费掉$length长度的数据
  493. * @param int $length
  494. * @return void
  495. */
  496. public function consumeRecvBuffer($length)
  497. {
  498. $this->_recvBuffer = substr($this->_recvBuffer, $length);
  499. }
  500. /**
  501. * 关闭连接
  502. * @param mixed $data
  503. * @void
  504. */
  505. public function close($data = null)
  506. {
  507. if($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED)
  508. {
  509. return false;
  510. }
  511. else
  512. {
  513. if($data !== null)
  514. {
  515. $this->send($data);
  516. }
  517. $this->_status = self::STATUS_CLOSING;
  518. }
  519. if($this->_sendBuffer === '')
  520. {
  521. $this->destroy();
  522. }
  523. }
  524. /**
  525. * 获得socket连接
  526. * @return resource
  527. */
  528. public function getSocket()
  529. {
  530. return $this->_socket;
  531. }
  532. /**
  533. * 检查发送缓冲区是否已满,如果满了尝试触发onBufferFull回调
  534. * @return void
  535. */
  536. protected function checkBufferIsFull()
  537. {
  538. if($this->maxSendBufferSize <= strlen($this->_sendBuffer))
  539. {
  540. if($this->onBufferFull)
  541. {
  542. try
  543. {
  544. call_user_func($this->onBufferFull, $this);
  545. }
  546. catch(Exception $e)
  547. {
  548. echo $e;
  549. }
  550. }
  551. }
  552. }
  553. /**
  554. * 销毁连接
  555. * @return void
  556. */
  557. public function destroy()
  558. {
  559. // 避免重复调用
  560. if($this->_status === self::STATUS_CLOSED)
  561. {
  562. return false;
  563. }
  564. // 删除事件监听
  565. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  566. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  567. // 关闭socket
  568. @fclose($this->_socket);
  569. // 从连接中删除
  570. if($this->worker)
  571. {
  572. unset($this->worker->connections[(int)$this->_socket]);
  573. }
  574. // 标记该连接已经关闭
  575. $this->_status = self::STATUS_CLOSED;
  576. // 触发onClose回调
  577. if($this->onClose)
  578. {
  579. try
  580. {
  581. call_user_func($this->onClose, $this);
  582. }
  583. catch (Exception $e)
  584. {
  585. self::$statistics['throw_exception']++;
  586. echo $e;
  587. }
  588. }
  589. }
  590. /**
  591. * 析构函数
  592. * @return void
  593. */
  594. public function __destruct()
  595. {
  596. // 统计数据
  597. self::$statistics['connection_count']--;
  598. }
  599. }