TcpConnection.php 18 KB

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