TcpConnection.php 18 KB

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