TcpConnection.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. * connection
  10. * @author walkor<walkor@workerman.net>
  11. */
  12. class TcpConnection extends ConnectionInterface
  13. {
  14. /**
  15. * when recv data from client ,how much bytes to read
  16. * @var unknown_type
  17. */
  18. const READ_BUFFER_SIZE = 8192;
  19. /**
  20. * connection status connecting
  21. * @var int
  22. */
  23. const STATUS_CONNECTING = 1;
  24. /**
  25. * connection status establish
  26. * @var int
  27. */
  28. const STATUS_ESTABLISH = 2;
  29. /**
  30. * connection status closing
  31. * @var int
  32. */
  33. const STATUS_CLOSING = 4;
  34. /**
  35. * connection status closed
  36. * @var int
  37. */
  38. const STATUS_CLOSED = 8;
  39. /**
  40. * when receive data, onMessage will be run
  41. * @var callback
  42. */
  43. public $onMessage = null;
  44. /**
  45. * when connection close, onClose will be run
  46. * @var callback
  47. */
  48. public $onClose = null;
  49. /**
  50. * when some thing wrong ,onError will be run
  51. * @var callback
  52. */
  53. public $onError = null;
  54. /**
  55. * protocol
  56. * @var string
  57. */
  58. public $protocol = '';
  59. /**
  60. * eventloop
  61. * @var EventInterface
  62. */
  63. protected $_event = null;
  64. /**
  65. * max send buffer size (Bytes)
  66. * @var int
  67. */
  68. public static $maxSendBufferSize = 1048576;
  69. /**
  70. * max package size (Bytes)
  71. * @var int
  72. */
  73. public static $maxPackageSize = 10485760;
  74. /**
  75. * the socket
  76. * @var resource
  77. */
  78. protected $_socket = null;
  79. /**
  80. * the buffer to send
  81. * @var string
  82. */
  83. protected $_sendBuffer = '';
  84. /**
  85. * the buffer read from socket
  86. * @var string
  87. */
  88. protected $_recvBuffer = '';
  89. /**
  90. * current package length
  91. * @var int
  92. */
  93. protected $_currentPackageLength = 0;
  94. /**
  95. * connection status
  96. * @var int
  97. */
  98. protected $_status = self::STATUS_ESTABLISH;
  99. /**
  100. * remote ip
  101. * @var string
  102. */
  103. protected $_remoteIp = '';
  104. /**
  105. * remote port
  106. * @var int
  107. */
  108. protected $_remotePort = 0;
  109. /**
  110. * remote address
  111. * @var string
  112. */
  113. protected $_remoteAddress = '';
  114. /**
  115. * create a connection
  116. * @param resource $socket
  117. * @param EventInterface $event
  118. */
  119. public function __construct($socket, EventInterface $event)
  120. {
  121. $this->_socket = $socket;
  122. stream_set_blocking($this->_socket, 0);
  123. $this->_event = $event;
  124. $this->_event->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  125. }
  126. /**
  127. * send buffer to client
  128. * @param string $send_buffer
  129. * @param bool $raw
  130. * @return void|boolean
  131. */
  132. public function send($send_buffer, $raw = false)
  133. {
  134. if($this->_status == self::STATUS_CLOSED)
  135. {
  136. return false;
  137. }
  138. if(false === $raw && $this->protocol)
  139. {
  140. $parser = $this->protocol;
  141. $send_buffer = $parser::encode($send_buffer, $this);
  142. }
  143. if($this->_sendBuffer === '')
  144. {
  145. $len = @fwrite($this->_socket, $send_buffer);
  146. if($len === strlen($send_buffer))
  147. {
  148. return true;
  149. }
  150. if($len > 0)
  151. {
  152. $this->_sendBuffer = substr($send_buffer, $len);
  153. }
  154. else
  155. {
  156. if(feof($this->_socket))
  157. {
  158. self::$statistics['send_fail']++;
  159. if($this->onError)
  160. {
  161. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'client closed');
  162. }
  163. $this->destroy();
  164. return false;
  165. }
  166. $this->_sendBuffer = $send_buffer;
  167. }
  168. $this->_event->add($this->_socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  169. return null;
  170. }
  171. else
  172. {
  173. // check send buffer size
  174. if(self::$maxSendBufferSize <= strlen($this->_sendBuffer) + strlen($send_buffer))
  175. {
  176. self::$statistics['send_fail']++;
  177. if($this->onError)
  178. {
  179. call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'send buffer full');
  180. }
  181. return false;
  182. }
  183. $this->_sendBuffer .= $send_buffer;
  184. }
  185. }
  186. /**
  187. * get remote ip
  188. * @return string
  189. */
  190. public function getRemoteIp()
  191. {
  192. if(!$this->_remoteIp)
  193. {
  194. $this->_remoteAddress = stream_socket_get_name($this->_socket, true);
  195. if($this->_remoteAddress)
  196. {
  197. list($this->_remoteIp, $this->_remotePort) = explode(':', $this->_remoteAddress, 2);
  198. $this->_remotePort = (int)$this->_remotePort;
  199. }
  200. }
  201. return $this->_remoteIp;
  202. }
  203. /**
  204. * get remote port
  205. */
  206. public function getRemotePort()
  207. {
  208. if(!$this->_remotePort)
  209. {
  210. $this->_remoteAddress = stream_socket_get_name($this->_socket, true);
  211. if($this->_remoteAddress)
  212. {
  213. list($this->_remoteIp, $this->_remotePort) = explode(':', $this->_remoteAddress, 2);
  214. $this->_remotePort = (int)$this->_remotePort;
  215. }
  216. }
  217. return $this->_remotePort;
  218. }
  219. /**
  220. * when socket is readable
  221. * @param resource $socket
  222. * @return void
  223. */
  224. public function baseRead($socket)
  225. {
  226. while($buffer = fread($socket, self::READ_BUFFER_SIZE))
  227. {
  228. $this->_recvBuffer .= $buffer;
  229. }
  230. if($this->_recvBuffer)
  231. {
  232. if(!$this->onMessage)
  233. {
  234. return ;
  235. }
  236. // protocol has been set
  237. if($this->protocol)
  238. {
  239. $parser = $this->protocol;
  240. while($this->_recvBuffer)
  241. {
  242. // already know current package length
  243. if($this->_currentPackageLength)
  244. {
  245. // we need more buffer
  246. if($this->_currentPackageLength > strlen($this->_recvBuffer))
  247. {
  248. break;
  249. }
  250. }
  251. else
  252. {
  253. // try to get the current package length
  254. $this->_currentPackageLength = $parser::input($this->_recvBuffer, $this);
  255. // need more buffer
  256. if($this->_currentPackageLength === 0)
  257. {
  258. break;
  259. }
  260. elseif($this->_currentPackageLength > 0 && $this->_currentPackageLength <= self::$maxPackageSize)
  261. {
  262. // need more buffer
  263. if($this->_currentPackageLength > strlen($this->_recvBuffer))
  264. {
  265. break;
  266. }
  267. }
  268. // error package
  269. else
  270. {
  271. $this->close('error package. package_length='.var_export($this->_currentPackageLength, true));
  272. }
  273. }
  274. // recvived the whole data
  275. self::$statistics['total_request']++;
  276. $one_request_buffer = substr($this->_recvBuffer, 0, $this->_currentPackageLength);
  277. $this->_recvBuffer = substr($this->_recvBuffer, $this->_currentPackageLength);
  278. $this->_currentPackageLength = 0;
  279. try
  280. {
  281. call_user_func($this->onMessage, $this, $parser::decode($one_request_buffer, $this));
  282. }
  283. catch(Exception $e)
  284. {
  285. self::$statistics['throw_exception']++;
  286. echo $e;
  287. }
  288. }
  289. return;
  290. }
  291. self::$statistics['total_request']++;
  292. // protocol not set
  293. try
  294. {
  295. call_user_func($this->onMessage, $this, $this->_recvBuffer);
  296. }
  297. catch(Exception $e)
  298. {
  299. self::$statistics['throw_exception']++;
  300. echo $e;
  301. }
  302. $this->_recvBuffer = '';
  303. }
  304. else if(feof($socket))
  305. {
  306. $this->destroy();
  307. return;
  308. }
  309. }
  310. /**
  311. * when socket is writeable
  312. * @return void
  313. */
  314. public function baseWrite()
  315. {
  316. $len = @fwrite($this->_socket, $this->_sendBuffer);
  317. if($len === strlen($this->_sendBuffer))
  318. {
  319. $this->_event->del($this->_socket, EventInterface::EV_WRITE);
  320. $this->_sendBuffer = '';
  321. if($this->_status == self::STATUS_CLOSING)
  322. {
  323. $this->destroy();
  324. }
  325. return true;
  326. }
  327. if($len > 0)
  328. {
  329. $this->_sendBuffer = substr($this->_sendBuffer, $len);
  330. }
  331. else
  332. {
  333. if(feof($this->_socket))
  334. {
  335. self::$statistics['send_fail']++;
  336. $this->destroy();
  337. }
  338. }
  339. }
  340. /**
  341. * consume recvBuffer
  342. * @param int $length
  343. */
  344. public function consumeRecvBuffer($length)
  345. {
  346. $this->_recvBuffer = substr($this->_recvBuffer, $length);
  347. }
  348. /**
  349. * close the connection
  350. * @param mixed $data
  351. * @void
  352. */
  353. public function close($data = null)
  354. {
  355. if($data !== null)
  356. {
  357. $this->send($data);
  358. }
  359. $this->_status = self::STATUS_CLOSING;
  360. if($this->_sendBuffer === '')
  361. {
  362. $this->destroy();
  363. }
  364. }
  365. /**
  366. * destroy the connection
  367. * @void
  368. */
  369. protected function destroy()
  370. {
  371. if($this->onClose)
  372. {
  373. try
  374. {
  375. call_user_func($this->onClose, $this);
  376. }
  377. catch (Exception $e)
  378. {
  379. self::$statistics['throw_exception']++;
  380. echo $e;
  381. }
  382. }
  383. $this->_event->del($this->_socket, EventInterface::EV_READ);
  384. $this->_event->del($this->_socket, EventInterface::EV_WRITE);
  385. @fclose($this->_socket);
  386. $this->_status = self::STATUS_CLOSED;
  387. }
  388. }