TcpConnection.php 16 KB

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