TcpConnection.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. * 使用的应用层协议,是协议类的名称
  57. * 值类似于 Workerman\\Protocols\\Http
  58. * @var string
  59. */
  60. public $protocol = '';
  61. /**
  62. * 发送缓冲区大小,当发送缓冲区满时,会尝试触发onError回调(如果有设置的话)
  63. * 如果没设置onError回调,发送缓冲区满,则后续发送的数据将被丢弃,
  64. * 直到发送缓冲区有空的位置
  65. * 注意 此值可以动态设置
  66. * 例如 Workerman\Connection\TcpConnection::$maxSendBufferSize=1024000;
  67. * @var int
  68. */
  69. public static $maxSendBufferSize = 1048576;
  70. /**
  71. * 能接受的最大数据包,为了防止恶意攻击,当数据包的大小大于此值时执行断开
  72. * 注意 此值可以动态设置
  73. * 例如 Workerman\Connection\TcpConnection::$maxPackageSize=1024000;
  74. * @var int
  75. */
  76. public static $maxPackageSize = 10485760;
  77. /**
  78. * 实际的socket资源
  79. * @var resource
  80. */
  81. protected $_socket = null;
  82. /**
  83. * 发送缓冲区
  84. * @var string
  85. */
  86. protected $_sendBuffer = '';
  87. /**
  88. * 接收缓冲区
  89. * @var string
  90. */
  91. protected $_recvBuffer = '';
  92. /**
  93. * 当前正在处理的数据包的包长(此值是协议的intput方法的返回值)
  94. * @var int
  95. */
  96. protected $_currentPackageLength = 0;
  97. /**
  98. * 当前的连接状态
  99. * @var int
  100. */
  101. protected $_status = self::STATUS_ESTABLISH;
  102. /**
  103. * 对端ip
  104. * @var string
  105. */
  106. protected $_remoteIp = '';
  107. /**
  108. * 对端端口
  109. * @var int
  110. */
  111. protected $_remotePort = 0;
  112. /**
  113. * 对端的地址 ip+port
  114. * 值类似于 192.168.1.100:3698
  115. * @var string
  116. */
  117. protected $_remoteAddress = '';
  118. /**
  119. * 构造函数
  120. * @param resource $socket
  121. * @param EventInterface $event
  122. */
  123. public function __construct($socket)
  124. {
  125. $this->_socket = $socket;
  126. stream_set_blocking($this->_socket, 0);
  127. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  128. }
  129. /**
  130. * 发送数据给对端
  131. * @param string $send_buffer
  132. * @param bool $raw
  133. * @return void|boolean
  134. */
  135. public function send($send_buffer, $raw = false)
  136. {
  137. // 如果连接已经关闭,则返回false
  138. if($this->_status == self::STATUS_CLOSED)
  139. {
  140. return false;
  141. }
  142. // 如果没有设置以原始数据发送,并且有设置协议。只协议编码
  143. if(false === $raw && $this->protocol)
  144. {
  145. $parser = $this->protocol;
  146. $send_buffer = $parser::encode($send_buffer, $this);
  147. }
  148. // 如果发送缓冲区为空,尝试直接发送
  149. if($this->_sendBuffer === '')
  150. {
  151. // 直接发送
  152. $len = @fwrite($this->_socket, $send_buffer);
  153. // 所有数据都发送完毕
  154. if($len === strlen($send_buffer))
  155. {
  156. return true;
  157. }
  158. // 只有部分数据发送成功
  159. if($len > 0)
  160. {
  161. // 未发送成功部分放入发送缓冲区
  162. $this->_sendBuffer = substr($send_buffer, $len);
  163. }
  164. else
  165. {
  166. // 如果连接断开
  167. if(feof($this->_socket))
  168. {
  169. // status统计发送失败次数
  170. self::$statistics['send_fail']++;
  171. // 如果有设置失败回调,则执行
  172. if($this->onError)
  173. {
  174. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'client closed');
  175. }
  176. // 销毁连接
  177. $this->destroy();
  178. return false;
  179. }
  180. // 连接未断开,发送失败,则把所有数据放入发送缓冲区
  181. $this->_sendBuffer = $send_buffer;
  182. }
  183. // 监听对端可写事件
  184. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  185. return null;
  186. }
  187. else
  188. {
  189. // 检查发送缓冲区是否已满
  190. if(self::$maxSendBufferSize <= strlen($this->_sendBuffer) + strlen($send_buffer))
  191. {
  192. // 为status命令统计发送失败次数
  193. self::$statistics['send_fail']++;
  194. // 如果有设置失败回调,则执行
  195. if($this->onError)
  196. {
  197. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'send buffer full');
  198. }
  199. return false;
  200. }
  201. // 将数据放入放缓冲区
  202. $this->_sendBuffer .= $send_buffer;
  203. }
  204. }
  205. /**
  206. * get remote ip
  207. * @return string
  208. */
  209. public function getRemoteIp()
  210. {
  211. if(!$this->_remoteIp)
  212. {
  213. $this->_remoteAddress = stream_socket_get_name($this->_socket, true);
  214. if($this->_remoteAddress)
  215. {
  216. list($this->_remoteIp, $this->_remotePort) = explode(':', $this->_remoteAddress, 2);
  217. $this->_remotePort = (int)$this->_remotePort;
  218. }
  219. }
  220. return $this->_remoteIp;
  221. }
  222. /**
  223. * get remote port
  224. */
  225. public function getRemotePort()
  226. {
  227. if(!$this->_remotePort)
  228. {
  229. $this->_remoteAddress = stream_socket_get_name($this->_socket, true);
  230. if($this->_remoteAddress)
  231. {
  232. list($this->_remoteIp, $this->_remotePort) = explode(':', $this->_remoteAddress, 2);
  233. $this->_remotePort = (int)$this->_remotePort;
  234. }
  235. }
  236. return $this->_remotePort;
  237. }
  238. /**
  239. * when socket is readable
  240. * @param resource $socket
  241. * @return void
  242. */
  243. public function baseRead($socket)
  244. {
  245. while($buffer = fread($socket, self::READ_BUFFER_SIZE))
  246. {
  247. $this->_recvBuffer .= $buffer;
  248. }
  249. if($this->_recvBuffer)
  250. {
  251. if(!$this->onMessage)
  252. {
  253. return ;
  254. }
  255. // protocol has been set
  256. if($this->protocol)
  257. {
  258. $parser = $this->protocol;
  259. while($this->_recvBuffer)
  260. {
  261. // already know current package length
  262. if($this->_currentPackageLength)
  263. {
  264. // we need more buffer
  265. if($this->_currentPackageLength > strlen($this->_recvBuffer))
  266. {
  267. break;
  268. }
  269. }
  270. else
  271. {
  272. // try to get the current package length
  273. $this->_currentPackageLength = $parser::input($this->_recvBuffer, $this);
  274. // need more buffer
  275. if($this->_currentPackageLength === 0)
  276. {
  277. break;
  278. }
  279. elseif($this->_currentPackageLength > 0 && $this->_currentPackageLength <= self::$maxPackageSize)
  280. {
  281. // need more buffer
  282. if($this->_currentPackageLength > strlen($this->_recvBuffer))
  283. {
  284. break;
  285. }
  286. }
  287. // error package
  288. else
  289. {
  290. $this->close('error package. package_length='.var_export($this->_currentPackageLength, true));
  291. }
  292. }
  293. // recvived the whole data
  294. self::$statistics['total_request']++;
  295. $one_request_buffer = substr($this->_recvBuffer, 0, $this->_currentPackageLength);
  296. $this->_recvBuffer = substr($this->_recvBuffer, $this->_currentPackageLength);
  297. $this->_currentPackageLength = 0;
  298. try
  299. {
  300. call_user_func($this->onMessage, $this, $parser::decode($one_request_buffer, $this));
  301. }
  302. catch(Exception $e)
  303. {
  304. self::$statistics['throw_exception']++;
  305. echo $e;
  306. }
  307. }
  308. if($this->_status !== self::STATUS_CLOSED && feof($socket))
  309. {
  310. $this->destroy();
  311. return;
  312. }
  313. return;
  314. }
  315. self::$statistics['total_request']++;
  316. // protocol not set
  317. try
  318. {
  319. call_user_func($this->onMessage, $this, $this->_recvBuffer);
  320. }
  321. catch(Exception $e)
  322. {
  323. self::$statistics['throw_exception']++;
  324. echo $e;
  325. }
  326. $this->_recvBuffer = '';
  327. if($this->_status !== self::STATUS_CLOSED && feof($socket))
  328. {
  329. $this->destroy();
  330. return;
  331. }
  332. }
  333. else if(feof($socket))
  334. {
  335. $this->destroy();
  336. return;
  337. }
  338. }
  339. /**
  340. * when socket is writeable
  341. * @return void
  342. */
  343. public function baseWrite()
  344. {
  345. $len = @fwrite($this->_socket, $this->_sendBuffer);
  346. if($len === strlen($this->_sendBuffer))
  347. {
  348. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  349. $this->_sendBuffer = '';
  350. if($this->_status == self::STATUS_CLOSING)
  351. {
  352. $this->destroy();
  353. }
  354. return true;
  355. }
  356. if($len > 0)
  357. {
  358. $this->_sendBuffer = substr($this->_sendBuffer, $len);
  359. }
  360. else
  361. {
  362. if(feof($this->_socket))
  363. {
  364. self::$statistics['send_fail']++;
  365. $this->destroy();
  366. }
  367. }
  368. }
  369. /**
  370. * consume recvBuffer
  371. * @param int $length
  372. */
  373. public function consumeRecvBuffer($length)
  374. {
  375. $this->_recvBuffer = substr($this->_recvBuffer, $length);
  376. }
  377. /**
  378. * close the connection
  379. * @param mixed $data
  380. * @void
  381. */
  382. public function close($data = null)
  383. {
  384. if($data !== null)
  385. {
  386. $this->send($data);
  387. }
  388. $this->_status = self::STATUS_CLOSING;
  389. if($this->_sendBuffer === '')
  390. {
  391. $this->destroy();
  392. }
  393. }
  394. /**
  395. * get socket
  396. * @return resource
  397. */
  398. public function getSocket()
  399. {
  400. return $this->_socket;
  401. }
  402. /**
  403. * destroy the connection
  404. * @void
  405. */
  406. protected function destroy()
  407. {
  408. self::$statistics['connection_count']--;
  409. if($this->onClose)
  410. {
  411. try
  412. {
  413. call_user_func($this->onClose, $this);
  414. }
  415. catch (Exception $e)
  416. {
  417. self::$statistics['throw_exception']++;
  418. echo $e;
  419. }
  420. }
  421. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  422. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  423. @fclose($this->_socket);
  424. $this->_status = self::STATUS_CLOSED;
  425. }
  426. }