TcpConnection.php 18 KB

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