TcpConnection.php 17 KB

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