TcpConnection.php 18 KB

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