gateway.class.php 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. /**
  15. * 数据发送相关
  16. * @version 3.0.12
  17. */
  18. /**
  19. * 数据发送相关
  20. */
  21. class Gateway
  22. {
  23. /**
  24. * gateway 实例
  25. *
  26. * @var object
  27. */
  28. protected static $businessWorker = null;
  29. /**
  30. * 注册中心地址
  31. *
  32. * @var string|array
  33. */
  34. public static $registerAddress = '127.0.0.1:1236';
  35. /**
  36. * 秘钥
  37. * @var string
  38. */
  39. public static $secretKey = '';
  40. /**
  41. * 链接超时时间
  42. * @var int
  43. */
  44. public static $connectTimeout = 3;
  45. /**
  46. * 与Gateway是否是长链接
  47. * @var bool
  48. */
  49. public static $persistentConnection = false;
  50. /**
  51. * 向所有客户端连接(或者 client_id_array 指定的客户端连接)广播消息
  52. *
  53. * @param string $message 向客户端发送的消息
  54. * @param array $client_id_array 客户端 id 数组
  55. * @param array $exclude_client_id 不给这些client_id发
  56. * @param bool $raw 是否发送原始数据(即不调用gateway的协议的encode方法)
  57. * @return void
  58. * @throws Exception
  59. */
  60. public static function sendToAll($message, $client_id_array = null, $exclude_client_id = null, $raw = false)
  61. {
  62. $gateway_data = GatewayProtocol::$empty;
  63. $gateway_data['cmd'] = GatewayProtocol::CMD_SEND_TO_ALL;
  64. $gateway_data['body'] = $message;
  65. if ($raw) {
  66. $gateway_data['flag'] |= GatewayProtocol::FLAG_NOT_CALL_ENCODE;
  67. }
  68. if ($exclude_client_id) {
  69. if (!is_array($exclude_client_id)) {
  70. $exclude_client_id = array($exclude_client_id);
  71. }
  72. if ($client_id_array) {
  73. $exclude_client_id = array_flip($exclude_client_id);
  74. }
  75. }
  76. if ($client_id_array) {
  77. if (!is_array($client_id_array)) {
  78. echo new \Exception('bad $client_id_array:'.var_export($client_id_array, true));
  79. return;
  80. }
  81. $data_array = array();
  82. foreach ($client_id_array as $client_id) {
  83. if (isset($exclude_client_id[$client_id])) {
  84. continue;
  85. }
  86. $address = Context::clientIdToAddress($client_id);
  87. if ($address) {
  88. $key = long2ip($address['local_ip']) . ":{$address['local_port']}";
  89. $data_array[$key][$address['connection_id']] = $address['connection_id'];
  90. }
  91. }
  92. foreach ($data_array as $addr => $connection_id_list) {
  93. $the_gateway_data = $gateway_data;
  94. $the_gateway_data['ext_data'] = json_encode(array('connections' => $connection_id_list));
  95. static::sendToGateway($addr, $the_gateway_data);
  96. }
  97. return;
  98. } elseif (empty($client_id_array) && is_array($client_id_array)) {
  99. return;
  100. }
  101. if (!$exclude_client_id) {
  102. return static::sendToAllGateway($gateway_data);
  103. }
  104. $address_connection_array = static::clientIdArrayToAddressArray($exclude_client_id);
  105. // 如果有businessWorker实例,说明运行在workerman环境中,通过businessWorker中的长连接发送数据
  106. if (static::$businessWorker) {
  107. foreach (static::$businessWorker->gatewayConnections as $address => $gateway_connection) {
  108. $gateway_data['ext_data'] = isset($address_connection_array[$address]) ?
  109. json_encode(array('exclude'=> $address_connection_array[$address])) : '';
  110. /** @var TcpConnection $gateway_connection */
  111. $gateway_connection->send($gateway_data);
  112. }
  113. } // 运行在其它环境中,通过注册中心得到gateway地址
  114. else {
  115. $all_addresses = static::getAllGatewayAddressesFromRegister();
  116. foreach ($all_addresses as $address) {
  117. $gateway_data['ext_data'] = isset($address_connection_array[$address]) ?
  118. json_encode(array('exclude'=> $address_connection_array[$address])) : '';
  119. static::sendToGateway($address, $gateway_data);
  120. }
  121. }
  122. }
  123. /**
  124. * 向某个client_id对应的连接发消息
  125. *
  126. * @param int $client_id
  127. * @param string $message
  128. * @return void
  129. */
  130. public static function sendToClient($client_id, $message)
  131. {
  132. return static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_SEND_TO_ONE, $message);
  133. }
  134. /**
  135. * 判断某个uid是否在线
  136. *
  137. * @param string $uid
  138. * @return int 0|1
  139. */
  140. public static function isUidOnline($uid)
  141. {
  142. return (int)static::getClientIdByUid($uid);
  143. }
  144. /**
  145. * 判断client_id对应的连接是否在线
  146. *
  147. * @param int $client_id
  148. * @return int 0|1
  149. */
  150. public static function isOnline($client_id)
  151. {
  152. $address_data = Context::clientIdToAddress($client_id);
  153. if (!$address_data) {
  154. return 0;
  155. }
  156. $address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
  157. if (isset(static::$businessWorker)) {
  158. if (!isset(static::$businessWorker->gatewayConnections[$address])) {
  159. return 0;
  160. }
  161. }
  162. $gateway_data = GatewayProtocol::$empty;
  163. $gateway_data['cmd'] = GatewayProtocol::CMD_IS_ONLINE;
  164. $gateway_data['connection_id'] = $address_data['connection_id'];
  165. return (int)static::sendAndRecv($address, $gateway_data);
  166. }
  167. /**
  168. * 获取所有在线用户的session,client_id为 key(弃用,请用getAllClientSessions代替)
  169. *
  170. * @param string $group
  171. * @return array
  172. */
  173. public static function getAllClientInfo($group = '')
  174. {
  175. echo "Warning: Gateway::getAllClientInfo is deprecated and will be removed in a future, please use Gateway::getAllClientSessions instead.";
  176. return static::getAllClientSessions($group);
  177. }
  178. /**
  179. * 获取所有在线client_id的session,client_id为 key
  180. *
  181. * @param string $group
  182. * @return array
  183. */
  184. public static function getAllClientSessions($group = '')
  185. {
  186. $gateway_data = GatewayProtocol::$empty;
  187. if (!$group) {
  188. $gateway_data['cmd'] = GatewayProtocol::CMD_GET_ALL_CLIENT_SESSIONS;
  189. } else {
  190. $gateway_data['cmd'] = GatewayProtocol::CMD_GET_CLIENT_SESSIONS_BY_GROUP;
  191. $gateway_data['ext_data'] = $group;
  192. }
  193. $status_data = array();
  194. $all_buffer_array = static::getBufferFromAllGateway($gateway_data);
  195. foreach ($all_buffer_array as $local_ip => $buffer_array) {
  196. foreach ($buffer_array as $local_port => $data) {
  197. if ($data) {
  198. foreach ($data as $connection_id => $session_buffer) {
  199. $client_id = Context::addressToClientId($local_ip, $local_port, $connection_id);
  200. if ($client_id === Context::$client_id) {
  201. $status_data[$client_id] = (array)$_SESSION;
  202. } else {
  203. $status_data[$client_id] = $session_buffer ? Context::sessionDecode($session_buffer) : array();
  204. }
  205. }
  206. }
  207. }
  208. }
  209. return $status_data;
  210. }
  211. /**
  212. * 获取某个组的连接信息(弃用,请用getClientSessionsByGroup代替)
  213. *
  214. * @param string $group
  215. * @return array
  216. */
  217. public static function getClientInfoByGroup($group)
  218. {
  219. echo "Warning: Gateway::getClientInfoByGroup is deprecated and will be removed in a future, please use Gateway::getClientSessionsByGroup instead.";
  220. return static::getAllClientSessions($group);
  221. }
  222. /**
  223. * 获取某个组的所有client_id的session信息
  224. *
  225. * @param string $group
  226. *
  227. * @return array
  228. */
  229. public static function getClientSessionsByGroup($group)
  230. {
  231. if (static::isValidGroupId($group)) {
  232. return static::getAllClientSessions($group);
  233. }
  234. return array();
  235. }
  236. /**
  237. * 获取所有在线client_id数
  238. *
  239. * @return int
  240. */
  241. public static function getAllClientIdCount()
  242. {
  243. return static::getClientCountByGroup();
  244. }
  245. /**
  246. * 获取所有在线client_id数(getAllClientIdCount的别名)
  247. *
  248. * @return int
  249. */
  250. public static function getAllClientCount()
  251. {
  252. return static::getAllClientIdCount();
  253. }
  254. /**
  255. * 获取某个组的在线client_id数
  256. *
  257. * @param string $group
  258. * @return int
  259. */
  260. public static function getClientIdCountByGroup($group = '')
  261. {
  262. $gateway_data = GatewayProtocol::$empty;
  263. $gateway_data['cmd'] = GatewayProtocol::CMD_GET_CLIENT_COUNT_BY_GROUP;
  264. $gateway_data['ext_data'] = $group;
  265. $total_count = 0;
  266. $all_buffer_array = static::getBufferFromAllGateway($gateway_data);
  267. foreach ($all_buffer_array as $local_ip => $buffer_array) {
  268. foreach ($buffer_array as $local_port => $count) {
  269. if ($count) {
  270. $total_count += $count;
  271. }
  272. }
  273. }
  274. return $total_count;
  275. }
  276. /**
  277. * getClientIdCountByGroup 函数的别名
  278. *
  279. * @param string $group
  280. * @return int
  281. */
  282. public static function getClientCountByGroup($group = '')
  283. {
  284. return static::getClientIdCountByGroup($group);
  285. }
  286. /**
  287. * 获取某个群组在线client_id列表
  288. *
  289. * @param string $group
  290. * @return array
  291. */
  292. public static function getClientIdListByGroup($group)
  293. {
  294. if (!static::isValidGroupId($group)) {
  295. return array();
  296. }
  297. $data = static::select(array('uid'), array('groups' => is_array($group) ? $group : array($group)));
  298. $client_id_map = array();
  299. foreach ($data as $local_ip => $buffer_array) {
  300. foreach ($buffer_array as $local_port => $items) {
  301. //$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
  302. foreach ($items as $connection_id => $info) {
  303. $client_id = Context::addressToClientId($local_ip, $local_port, $connection_id);
  304. $client_id_map[$client_id] = $client_id;
  305. }
  306. }
  307. }
  308. return $client_id_map;
  309. }
  310. /**
  311. * 获取集群所有在线client_id列表
  312. *
  313. * @return array
  314. */
  315. public static function getAllClientIdList()
  316. {
  317. return static::formatClientIdFromGatewayBuffer(static::select(array('uid')));
  318. }
  319. /**
  320. * 格式化client_id
  321. *
  322. * @param $data
  323. * @return array
  324. */
  325. protected static function formatClientIdFromGatewayBuffer($data)
  326. {
  327. $client_id_list = array();
  328. foreach ($data as $local_ip => $buffer_array) {
  329. foreach ($buffer_array as $local_port => $items) {
  330. //$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
  331. foreach ($items as $connection_id => $info) {
  332. $client_id = Context::addressToClientId($local_ip, $local_port, $connection_id);
  333. $client_id_list[$client_id] = $client_id;
  334. }
  335. }
  336. }
  337. return $client_id_list;
  338. }
  339. /**
  340. * 获取与 uid 绑定的 client_id 列表
  341. *
  342. * @param string $uid
  343. * @return array
  344. */
  345. public static function getClientIdByUid($uid)
  346. {
  347. $gateway_data = GatewayProtocol::$empty;
  348. $gateway_data['cmd'] = GatewayProtocol::CMD_GET_CLIENT_ID_BY_UID;
  349. $gateway_data['ext_data'] = $uid;
  350. $client_list = array();
  351. $all_buffer_array = static::getBufferFromAllGateway($gateway_data);
  352. foreach ($all_buffer_array as $local_ip => $buffer_array) {
  353. foreach ($buffer_array as $local_port => $connection_id_array) {
  354. if ($connection_id_array) {
  355. foreach ($connection_id_array as $connection_id) {
  356. $client_list[] = Context::addressToClientId($local_ip, $local_port, $connection_id);
  357. }
  358. }
  359. }
  360. }
  361. return $client_list;
  362. }
  363. /**
  364. * 获取某个群组在线uid列表
  365. *
  366. * @param string $group
  367. * @return array
  368. */
  369. public static function getUidListByGroup($group)
  370. {
  371. if (!static::isValidGroupId($group)) {
  372. return array();
  373. }
  374. $group = is_array($group) ? $group : array($group);
  375. $data = static::select(array('uid'), array('groups' => $group));
  376. $uid_map = array();
  377. foreach ($data as $local_ip => $buffer_array) {
  378. foreach ($buffer_array as $local_port => $items) {
  379. //$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
  380. foreach ($items as $connection_id => $info) {
  381. if (!empty($info['uid'])) {
  382. $uid_map[$info['uid']] = $info['uid'];
  383. }
  384. }
  385. }
  386. }
  387. return $uid_map;
  388. }
  389. /**
  390. * 获取某个群组在线uid数
  391. *
  392. * @param string $group
  393. * @return int
  394. */
  395. public static function getUidCountByGroup($group)
  396. {
  397. if (static::isValidGroupId($group)) {
  398. return count(static::getUidListByGroup($group));
  399. }
  400. return 0;
  401. }
  402. /**
  403. * 获取全局在线uid列表
  404. *
  405. * @return array
  406. */
  407. public static function getAllUidList()
  408. {
  409. $data = static::select(array('uid'));
  410. $uid_map = array();
  411. foreach ($data as $local_ip => $buffer_array) {
  412. foreach ($buffer_array as $local_port => $items) {
  413. //$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
  414. foreach ($items as $connection_id => $info) {
  415. if (!empty($info['uid'])) {
  416. $uid_map[$info['uid']] = $info['uid'];
  417. }
  418. }
  419. }
  420. }
  421. return $uid_map;
  422. }
  423. /**
  424. * 获取全局在线uid数
  425. * @return int
  426. */
  427. public static function getAllUidCount()
  428. {
  429. return count(static::getAllUidList());
  430. }
  431. /**
  432. * 通过client_id获取uid
  433. *
  434. * @param $client_id
  435. * @return mixed
  436. */
  437. public static function getUidByClientId($client_id)
  438. {
  439. $data = static::select(array('uid'), array('client_id'=>array($client_id)));
  440. foreach ($data as $local_ip => $buffer_array) {
  441. foreach ($buffer_array as $local_port => $items) {
  442. //$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
  443. foreach ($items as $info) {
  444. return $info['uid'];
  445. }
  446. }
  447. }
  448. }
  449. /**
  450. * 获取所有在线的群组id
  451. *
  452. * @return array
  453. */
  454. public static function getAllGroupIdList()
  455. {
  456. $gateway_data = GatewayProtocol::$empty;
  457. $gateway_data['cmd'] = GatewayProtocol::CMD_GET_GROUP_ID_LIST;
  458. $group_id_list = array();
  459. $all_buffer_array = static::getBufferFromAllGateway($gateway_data);
  460. foreach ($all_buffer_array as $local_ip => $buffer_array) {
  461. foreach ($buffer_array as $local_port => $group_id_array) {
  462. if (is_array($group_id_array)) {
  463. foreach ($group_id_array as $group_id) {
  464. if (!isset($group_id_list[$group_id])) {
  465. $group_id_list[$group_id] = $group_id;
  466. }
  467. }
  468. }
  469. }
  470. }
  471. return $group_id_list;
  472. }
  473. /**
  474. * 获取所有在线分组的uid数量,也就是每个分组的在线用户数
  475. *
  476. * @return array
  477. */
  478. public static function getAllGroupUidCount()
  479. {
  480. $group_uid_map = static::getAllGroupUidList();
  481. $group_uid_count_map = array();
  482. foreach ($group_uid_map as $group_id => $uid_list) {
  483. $group_uid_count_map[$group_id] = count($uid_list);
  484. }
  485. return $group_uid_count_map;
  486. }
  487. /**
  488. * 获取所有分组uid在线列表
  489. *
  490. * @return array
  491. */
  492. public static function getAllGroupUidList()
  493. {
  494. $data = static::select(array('uid','groups'));
  495. $group_uid_map = array();
  496. foreach ($data as $local_ip => $buffer_array) {
  497. foreach ($buffer_array as $local_port => $items) {
  498. //$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
  499. foreach ($items as $connection_id => $info) {
  500. if (empty($info['uid']) || empty($info['groups'])) {
  501. break;
  502. }
  503. $uid = $info['uid'];
  504. foreach ($info['groups'] as $group_id) {
  505. if(!isset($group_uid_map[$group_id])) {
  506. $group_uid_map[$group_id] = array();
  507. }
  508. $group_uid_map[$group_id][$uid] = $uid;
  509. }
  510. }
  511. }
  512. }
  513. return $group_uid_map;
  514. }
  515. /**
  516. * 获取所有群组在线client_id列表
  517. *
  518. * @return array
  519. */
  520. public static function getAllGroupClientIdList()
  521. {
  522. $data = static::select(array('groups'));
  523. $group_client_id_map = array();
  524. foreach ($data as $local_ip => $buffer_array) {
  525. foreach ($buffer_array as $local_port => $items) {
  526. //$items = ['connection_id'=>['uid'=>x, 'group'=>[x,x..], 'session'=>[..]], 'client_id'=>[..], ..];
  527. foreach ($items as $connection_id => $info) {
  528. if (empty($info['groups'])) {
  529. break;
  530. }
  531. $client_id = Context::addressToClientId($local_ip, $local_port, $connection_id);
  532. foreach ($info['groups'] as $group_id) {
  533. if(!isset($group_client_id_map[$group_id])) {
  534. $group_client_id_map[$group_id] = array();
  535. }
  536. $group_client_id_map[$group_id][$client_id] = $client_id;
  537. }
  538. }
  539. }
  540. }
  541. return $group_client_id_map;
  542. }
  543. /**
  544. * 获取所有群组在线client_id数量,也就是获取每个群组在线连接数
  545. *
  546. * @return array
  547. */
  548. public static function getAllGroupClientIdCount()
  549. {
  550. $group_client_map = static::getAllGroupClientIdList();
  551. $group_client_count_map = array();
  552. foreach ($group_client_map as $group_id => $client_id_list) {
  553. $group_client_count_map[$group_id] = count($client_id_list);
  554. }
  555. return $group_client_count_map;
  556. }
  557. /**
  558. * 根据条件到gateway搜索数据
  559. *
  560. * @param array $fields
  561. * @param array $where
  562. * @return array
  563. */
  564. protected static function select($fields = array('session','uid','groups'), $where = array())
  565. {
  566. $t = microtime(true);
  567. $gateway_data = GatewayProtocol::$empty;
  568. $gateway_data['cmd'] = GatewayProtocol::CMD_SELECT;
  569. $gateway_data['ext_data'] = array('fields' => $fields, 'where' => $where);
  570. $gateway_data_list = array();
  571. // 有client_id,能计算出需要和哪些gateway通讯,只和必要的gateway通讯能降低系统负载
  572. if (isset($where['client_id'])) {
  573. $client_id_list = $where['client_id'];
  574. unset($gateway_data['ext_data']['where']['client_id']);
  575. $gateway_data['ext_data']['where']['connection_id'] = array();
  576. foreach ($client_id_list as $client_id) {
  577. $address_data = Context::clientIdToAddress($client_id);
  578. if (!$address_data) {
  579. continue;
  580. }
  581. $address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
  582. if (!isset($gateway_data_list[$address])) {
  583. $gateway_data_list[$address] = $gateway_data;
  584. }
  585. $gateway_data_list[$address]['ext_data']['where']['connection_id'][$address_data['connection_id']] = $address_data['connection_id'];
  586. }
  587. foreach ($gateway_data_list as $address => $item) {
  588. $gateway_data_list[$address]['ext_data'] = json_encode($item['ext_data']);
  589. }
  590. // 有其它条件,则还是需要向所有gateway发送
  591. if (count($where) !== 1) {
  592. $gateway_data['ext_data'] = json_encode($gateway_data['ext_data']);
  593. foreach (static::getAllGatewayAddress() as $address) {
  594. if (!isset($gateway_data_list[$address])) {
  595. $gateway_data_list[$address] = $gateway_data;
  596. }
  597. }
  598. }
  599. $data = static::getBufferFromSomeGateway($gateway_data_list);
  600. } else {
  601. $gateway_data['ext_data'] = json_encode($gateway_data['ext_data']);
  602. $data = static::getBufferFromAllGateway($gateway_data);
  603. }
  604. return $data;
  605. }
  606. /**
  607. * 生成验证包,用于验证此客户端的合法性
  608. *
  609. * @return string
  610. */
  611. protected static function generateAuthBuffer()
  612. {
  613. $gateway_data = GatewayProtocol::$empty;
  614. $gateway_data['cmd'] = GatewayProtocol::CMD_GATEWAY_CLIENT_CONNECT;
  615. $gateway_data['body'] = json_encode(array(
  616. 'secret_key' => static::$secretKey,
  617. ));
  618. return GatewayProtocol::encode($gateway_data);
  619. }
  620. /**
  621. * 批量向某些gateway发包,并得到返回数组
  622. *
  623. * @param array $gateway_data_array
  624. * @return array
  625. * @throws Exception
  626. */
  627. protected static function getBufferFromSomeGateway($gateway_data_array)
  628. {
  629. $gateway_buffer_array = array();
  630. $auth_buffer = static::$secretKey ? static::generateAuthBuffer() : '';
  631. foreach ($gateway_data_array as $address => $gateway_data) {
  632. if ($auth_buffer) {
  633. $gateway_buffer_array[$address] = $auth_buffer.GatewayProtocol::encode($gateway_data);
  634. } else {
  635. $gateway_buffer_array[$address] = GatewayProtocol::encode($gateway_data);
  636. }
  637. }
  638. return static::getBufferFromGateway($gateway_buffer_array);
  639. }
  640. /**
  641. * 批量向所有 gateway 发包,并得到返回数组
  642. *
  643. * @param string $gateway_data
  644. * @return array
  645. * @throws Exception
  646. */
  647. protected static function getBufferFromAllGateway($gateway_data)
  648. {
  649. $addresses = static::getAllGatewayAddress();
  650. $gateway_buffer_array = array();
  651. $gateway_buffer = GatewayProtocol::encode($gateway_data);
  652. $gateway_buffer = static::$secretKey ? static::generateAuthBuffer() . $gateway_buffer : $gateway_buffer;
  653. foreach ($addresses as $address) {
  654. $gateway_buffer_array[$address] = $gateway_buffer;
  655. }
  656. return static::getBufferFromGateway($gateway_buffer_array);
  657. }
  658. /**
  659. * 获取所有gateway内部通讯地址
  660. *
  661. * @return array
  662. * @throws Exception
  663. */
  664. protected static function getAllGatewayAddress()
  665. {
  666. if (isset(static::$businessWorker)) {
  667. $addresses = static::$businessWorker->getAllGatewayAddresses();
  668. if (empty($addresses)) {
  669. throw new Exception('businessWorker::getAllGatewayAddresses return empty');
  670. }
  671. } else {
  672. $addresses = static::getAllGatewayAddressesFromRegister();
  673. if (empty($addresses)) {
  674. return array();
  675. }
  676. }
  677. return $addresses;
  678. }
  679. /**
  680. * 批量向gateway发送并获取数据
  681. * @param $gateway_buffer_array
  682. * @return array
  683. */
  684. protected static function getBufferFromGateway($gateway_buffer_array)
  685. {
  686. $client_array = $status_data = $client_address_map = $receive_buffer_array = $recv_length_array = array();
  687. // 批量向所有gateway进程发送请求数据
  688. foreach ($gateway_buffer_array as $address => $gateway_buffer) {
  689. $client = stream_socket_client("tcp://$address", $errno, $errmsg, static::$connectTimeout);
  690. if ($client && strlen($gateway_buffer) === stream_socket_sendto($client, $gateway_buffer)) {
  691. $socket_id = (int)$client;
  692. $client_array[$socket_id] = $client;
  693. $client_address_map[$socket_id] = explode(':', $address);
  694. $receive_buffer_array[$socket_id] = '';
  695. }
  696. }
  697. // 超时5秒
  698. $timeout = 5;
  699. $time_start = microtime(true);
  700. // 批量接收请求
  701. while (count($client_array) > 0) {
  702. $write = $except = array();
  703. $read = $client_array;
  704. if (@stream_select($read, $write, $except, $timeout)) {
  705. foreach ($read as $client) {
  706. $socket_id = (int)$client;
  707. $buffer = stream_socket_recvfrom($client, 65535);
  708. if ($buffer !== '' && $buffer !== false) {
  709. $receive_buffer_array[$socket_id] .= $buffer;
  710. $receive_length = strlen($receive_buffer_array[$socket_id]);
  711. if (empty($recv_length_array[$socket_id]) && $receive_length >= 4) {
  712. $recv_length_array[$socket_id] = current(unpack('N', $receive_buffer_array[$socket_id]));
  713. }
  714. if (!empty($recv_length_array[$socket_id]) && $receive_length >= $recv_length_array[$socket_id] + 4) {
  715. unset($client_array[$socket_id]);
  716. }
  717. } elseif (feof($client)) {
  718. unset($client_array[$socket_id]);
  719. }
  720. }
  721. }
  722. if (microtime(true) - $time_start > $timeout) {
  723. break;
  724. }
  725. }
  726. $format_buffer_array = array();
  727. foreach ($receive_buffer_array as $socket_id => $buffer) {
  728. $local_ip = ip2long($client_address_map[$socket_id][0]);
  729. $local_port = $client_address_map[$socket_id][1];
  730. $format_buffer_array[$local_ip][$local_port] = unserialize(substr($buffer, 4));
  731. }
  732. return $format_buffer_array;
  733. }
  734. /**
  735. * 踢掉某个客户端,并以$message通知被踢掉客户端
  736. *
  737. * @param int $client_id
  738. * @param string $message
  739. * @return void
  740. */
  741. public static function closeClient($client_id, $message = null)
  742. {
  743. if ($client_id === Context::$client_id) {
  744. return static::closeCurrentClient($message);
  745. } // 不是发给当前用户则使用存储中的地址
  746. else {
  747. $address_data = Context::clientIdToAddress($client_id);
  748. if (!$address_data) {
  749. return false;
  750. }
  751. $address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
  752. return static::kickAddress($address, $address_data['connection_id'], $message);
  753. }
  754. }
  755. /**
  756. * 踢掉某个客户端并直接立即销毁相关连接
  757. *
  758. * @param int $client_id
  759. * @return bool
  760. */
  761. public static function destoryClient($client_id)
  762. {
  763. if ($client_id === Context::$client_id) {
  764. return static::destoryCurrentClient();
  765. } // 不是发给当前用户则使用存储中的地址
  766. else {
  767. $address_data = Context::clientIdToAddress($client_id);
  768. if (!$address_data) {
  769. return false;
  770. }
  771. $address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
  772. return static::destroyAddress($address, $address_data['connection_id']);
  773. }
  774. }
  775. /**
  776. * 踢掉当前客户端并直接立即销毁相关连接
  777. *
  778. * @return bool
  779. * @throws Exception
  780. */
  781. public static function destoryCurrentClient()
  782. {
  783. if (!Context::$connection_id) {
  784. throw new Exception('destoryCurrentClient can not be called in async context');
  785. }
  786. $address = long2ip(Context::$local_ip) . ':' . Context::$local_port;
  787. return static::destroyAddress($address, Context::$connection_id);
  788. }
  789. /**
  790. * 将 client_id 与 uid 绑定
  791. *
  792. * @param int $client_id
  793. * @param int|string $uid
  794. * @return void
  795. */
  796. public static function bindUid($client_id, $uid)
  797. {
  798. static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_BIND_UID, '', $uid);
  799. }
  800. /**
  801. * 将 client_id 与 uid 解除绑定
  802. *
  803. * @param int $client_id
  804. * @param int|string $uid
  805. * @return void
  806. */
  807. public static function unbindUid($client_id, $uid)
  808. {
  809. static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_UNBIND_UID, '', $uid);
  810. }
  811. /**
  812. * 将 client_id 加入组
  813. *
  814. * @param int $client_id
  815. * @param int|string $group
  816. * @return void
  817. */
  818. public static function joinGroup($client_id, $group)
  819. {
  820. static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_JOIN_GROUP, '', $group);
  821. }
  822. /**
  823. * 将 client_id 离开组
  824. *
  825. * @param int $client_id
  826. * @param int|string $group
  827. *
  828. * @return void
  829. */
  830. public static function leaveGroup($client_id, $group)
  831. {
  832. static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_LEAVE_GROUP, '', $group);
  833. }
  834. /**
  835. * 取消分组
  836. *
  837. * @param int|string $group
  838. *
  839. * @return void
  840. */
  841. public static function ungroup($group)
  842. {
  843. if (!static::isValidGroupId($group)) {
  844. return false;
  845. }
  846. $gateway_data = GatewayProtocol::$empty;
  847. $gateway_data['cmd'] = GatewayProtocol::CMD_UNGROUP;
  848. $gateway_data['ext_data'] = $group;
  849. return static::sendToAllGateway($gateway_data);
  850. }
  851. /**
  852. * 向所有 uid 发送
  853. *
  854. * @param int|string|array $uid
  855. * @param string $message
  856. *
  857. * @return void
  858. */
  859. public static function sendToUid($uid, $message)
  860. {
  861. $gateway_data = GatewayProtocol::$empty;
  862. $gateway_data['cmd'] = GatewayProtocol::CMD_SEND_TO_UID;
  863. $gateway_data['body'] = $message;
  864. if (!is_array($uid)) {
  865. $uid = array($uid);
  866. }
  867. $gateway_data['ext_data'] = json_encode($uid);
  868. static::sendToAllGateway($gateway_data);
  869. }
  870. /**
  871. * 向 group 发送
  872. *
  873. * @param int|string|array $group 组(不允许是 0 '0' false null array()等为空的值)
  874. * @param string $message 消息
  875. * @param array $exclude_client_id 不给这些client_id发
  876. * @param bool $raw 发送原始数据(即不调用gateway的协议的encode方法)
  877. *
  878. * @return void
  879. */
  880. public static function sendToGroup($group, $message, $exclude_client_id = null, $raw = false)
  881. {
  882. if (!static::isValidGroupId($group)) {
  883. return false;
  884. }
  885. $gateway_data = GatewayProtocol::$empty;
  886. $gateway_data['cmd'] = GatewayProtocol::CMD_SEND_TO_GROUP;
  887. $gateway_data['body'] = $message;
  888. if ($raw) {
  889. $gateway_data['flag'] |= GatewayProtocol::FLAG_NOT_CALL_ENCODE;
  890. }
  891. if (!is_array($group)) {
  892. $group = array($group);
  893. }
  894. // 分组发送,没有排除的client_id,直接发送
  895. $default_ext_data_buffer = json_encode(array('group'=> $group, 'exclude'=> null));
  896. if (empty($exclude_client_id)) {
  897. $gateway_data['ext_data'] = $default_ext_data_buffer;
  898. return static::sendToAllGateway($gateway_data);
  899. }
  900. // 分组发送,有排除的client_id,需要将client_id转换成对应gateway进程内的connectionId
  901. if (!is_array($exclude_client_id)) {
  902. $exclude_client_id = array($exclude_client_id);
  903. }
  904. $address_connection_array = static::clientIdArrayToAddressArray($exclude_client_id);
  905. // 如果有businessWorker实例,说明运行在workerman环境中,通过businessWorker中的长连接发送数据
  906. if (static::$businessWorker) {
  907. foreach (static::$businessWorker->gatewayConnections as $address => $gateway_connection) {
  908. $gateway_data['ext_data'] = isset($address_connection_array[$address]) ?
  909. json_encode(array('group'=> $group, 'exclude'=> $address_connection_array[$address])) :
  910. $default_ext_data_buffer;
  911. /** @var TcpConnection $gateway_connection */
  912. $gateway_connection->send($gateway_data);
  913. }
  914. } // 运行在其它环境中,通过注册中心得到gateway地址
  915. else {
  916. $addresses = static::getAllGatewayAddressesFromRegister();
  917. foreach ($addresses as $address) {
  918. $gateway_data['ext_data'] = isset($address_connection_array[$address]) ?
  919. json_encode(array('group'=> $group, 'exclude'=> $address_connection_array[$address])) :
  920. $default_ext_data_buffer;
  921. static::sendToGateway($address, $gateway_data);
  922. }
  923. }
  924. }
  925. /**
  926. * 更新 session,框架自动调用,开发者不要调用
  927. *
  928. * @param int $client_id
  929. * @param string $session_str
  930. * @return bool
  931. */
  932. public static function setSocketSession($client_id, $session_str)
  933. {
  934. return static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_SET_SESSION, '', $session_str);
  935. }
  936. /**
  937. * 设置 session,原session值会被覆盖
  938. *
  939. * @param int $client_id
  940. * @param array $session
  941. *
  942. * @return void
  943. */
  944. public static function setSession($client_id, array $session)
  945. {
  946. if (Context::$client_id === $client_id) {
  947. $_SESSION = $session;
  948. Context::$old_session = $_SESSION;
  949. }
  950. static::setSocketSession($client_id, Context::sessionEncode($session));
  951. }
  952. /**
  953. * 更新 session,实际上是与老的session合并
  954. *
  955. * @param int $client_id
  956. * @param array $session
  957. *
  958. * @return void
  959. */
  960. public static function updateSession($client_id, array $session)
  961. {
  962. if (Context::$client_id === $client_id) {
  963. $_SESSION = array_replace_recursive((array)$_SESSION, $session);
  964. Context::$old_session = $_SESSION;
  965. }
  966. static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_UPDATE_SESSION, '', Context::sessionEncode($session));
  967. }
  968. /**
  969. * 获取某个client_id的session
  970. *
  971. * @param int $client_id
  972. * @return mixed false表示出错、null表示用户不存在、array表示具体的session信息
  973. */
  974. public static function getSession($client_id)
  975. {
  976. $address_data = Context::clientIdToAddress($client_id);
  977. if (!$address_data) {
  978. return false;
  979. }
  980. $address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
  981. if (isset(static::$businessWorker)) {
  982. if (!isset(static::$businessWorker->gatewayConnections[$address])) {
  983. return null;
  984. }
  985. }
  986. $gateway_data = GatewayProtocol::$empty;
  987. $gateway_data['cmd'] = GatewayProtocol::CMD_GET_SESSION_BY_CLIENT_ID;
  988. $gateway_data['connection_id'] = $address_data['connection_id'];
  989. return static::sendAndRecv($address, $gateway_data);
  990. }
  991. /**
  992. * 向某个用户网关发送命令和消息
  993. *
  994. * @param int $client_id
  995. * @param int $cmd
  996. * @param string $message
  997. * @param string $ext_data
  998. * @return boolean
  999. */
  1000. protected static function sendCmdAndMessageToClient($client_id, $cmd, $message, $ext_data = '')
  1001. {
  1002. // 如果是发给当前用户则直接获取上下文中的地址
  1003. if ($client_id === Context::$client_id || $client_id === null) {
  1004. $address = long2ip(Context::$local_ip) . ':' . Context::$local_port;
  1005. $connection_id = Context::$connection_id;
  1006. } else {
  1007. $address_data = Context::clientIdToAddress($client_id);
  1008. if (!$address_data) {
  1009. return false;
  1010. }
  1011. $address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
  1012. $connection_id = $address_data['connection_id'];
  1013. }
  1014. $gateway_data = GatewayProtocol::$empty;
  1015. $gateway_data['cmd'] = $cmd;
  1016. $gateway_data['connection_id'] = $connection_id;
  1017. $gateway_data['body'] = $message;
  1018. if (!empty($ext_data)) {
  1019. $gateway_data['ext_data'] = $ext_data;
  1020. }
  1021. return static::sendToGateway($address, $gateway_data);
  1022. }
  1023. /**
  1024. * 发送数据并返回
  1025. *
  1026. * @param int $address
  1027. * @param mixed $data
  1028. * @return bool
  1029. * @throws Exception
  1030. */
  1031. protected static function sendAndRecv($address, $data)
  1032. {
  1033. $buffer = GatewayProtocol::encode($data);
  1034. $buffer = static::$secretKey ? static::generateAuthBuffer() . $buffer : $buffer;
  1035. $client = stream_socket_client("tcp://$address", $errno, $errmsg, static::$connectTimeout);
  1036. if (!$client) {
  1037. throw new Exception("can not connect to tcp://$address $errmsg");
  1038. }
  1039. if (strlen($buffer) === stream_socket_sendto($client, $buffer)) {
  1040. $timeout = 5;
  1041. // 阻塞读
  1042. stream_set_blocking($client, 1);
  1043. // 1秒超时
  1044. stream_set_timeout($client, 1);
  1045. $all_buffer = '';
  1046. $time_start = microtime(true);
  1047. $pack_len = 0;
  1048. while (1) {
  1049. $buf = stream_socket_recvfrom($client, 655350);
  1050. if ($buf !== '' && $buf !== false) {
  1051. $all_buffer .= $buf;
  1052. } else {
  1053. if (feof($client)) {
  1054. throw new Exception("connection close tcp://$address");
  1055. } elseif (microtime(true) - $time_start > $timeout) {
  1056. break;
  1057. }
  1058. continue;
  1059. }
  1060. $recv_len = strlen($all_buffer);
  1061. if (!$pack_len && $recv_len >= 4) {
  1062. $pack_len= current(unpack('N', $all_buffer));
  1063. }
  1064. // 回复的数据都是以\n结尾
  1065. if (($pack_len && $recv_len >= $pack_len + 4) || microtime(true) - $time_start > $timeout) {
  1066. break;
  1067. }
  1068. }
  1069. // 返回结果
  1070. return unserialize(substr($all_buffer, 4));
  1071. } else {
  1072. throw new Exception("sendAndRecv($address, \$bufer) fail ! Can not send data!", 502);
  1073. }
  1074. }
  1075. /**
  1076. * 发送数据到网关
  1077. *
  1078. * @param string $address
  1079. * @param array $gateway_data
  1080. * @return bool
  1081. */
  1082. protected static function sendToGateway($address, $gateway_data)
  1083. {
  1084. return static::sendBufferToGateway($address, GatewayProtocol::encode($gateway_data));
  1085. }
  1086. /**
  1087. * 发送buffer数据到网关
  1088. * @param string $address
  1089. * @param string $gateway_buffer
  1090. * @return bool
  1091. */
  1092. protected static function sendBufferToGateway($address, $gateway_buffer)
  1093. {
  1094. // 有$businessWorker说明是workerman环境,使用$businessWorker发送数据
  1095. if (static::$businessWorker) {
  1096. if (!isset(static::$businessWorker->gatewayConnections[$address])) {
  1097. return false;
  1098. }
  1099. return static::$businessWorker->gatewayConnections[$address]->send($gateway_buffer, true);
  1100. }
  1101. // 非workerman环境
  1102. $gateway_buffer = static::$secretKey ? static::generateAuthBuffer() . $gateway_buffer : $gateway_buffer;
  1103. $flag = static::$persistentConnection ? STREAM_CLIENT_PERSISTENT | STREAM_CLIENT_CONNECT : STREAM_CLIENT_CONNECT;
  1104. $client = stream_socket_client("tcp://$address", $errno, $errmsg, static::$connectTimeout, $flag);
  1105. return strlen($gateway_buffer) == stream_socket_sendto($client, $gateway_buffer);
  1106. }
  1107. /**
  1108. * 向所有 gateway 发送数据
  1109. *
  1110. * @param string $gateway_data
  1111. * @throws Exception
  1112. *
  1113. * @return void
  1114. */
  1115. protected static function sendToAllGateway($gateway_data)
  1116. {
  1117. $buffer = GatewayProtocol::encode($gateway_data);
  1118. // 如果有businessWorker实例,说明运行在workerman环境中,通过businessWorker中的长连接发送数据
  1119. if (static::$businessWorker) {
  1120. foreach (static::$businessWorker->gatewayConnections as $gateway_connection) {
  1121. /** @var TcpConnection $gateway_connection */
  1122. $gateway_connection->send($buffer, true);
  1123. }
  1124. } // 运行在其它环境中,通过注册中心得到gateway地址
  1125. else {
  1126. $all_addresses = static::getAllGatewayAddressesFromRegister();
  1127. foreach ($all_addresses as $address) {
  1128. static::sendBufferToGateway($address, $buffer);
  1129. }
  1130. }
  1131. }
  1132. /**
  1133. * 踢掉某个网关的 socket
  1134. *
  1135. * @param string $address
  1136. * @param int $connection_id
  1137. * @return bool
  1138. */
  1139. protected static function kickAddress($address, $connection_id, $message)
  1140. {
  1141. $gateway_data = GatewayProtocol::$empty;
  1142. $gateway_data['cmd'] = GatewayProtocol::CMD_KICK;
  1143. $gateway_data['connection_id'] = $connection_id;
  1144. $gateway_data['body'] = $message;
  1145. return static::sendToGateway($address, $gateway_data);
  1146. }
  1147. /**
  1148. * 销毁某个网关的 socket
  1149. *
  1150. * @param string $address
  1151. * @param int $connection_id
  1152. * @return bool
  1153. */
  1154. protected static function destroyAddress($address, $connection_id)
  1155. {
  1156. $gateway_data = GatewayProtocol::$empty;
  1157. $gateway_data['cmd'] = GatewayProtocol::CMD_DESTROY;
  1158. $gateway_data['connection_id'] = $connection_id;
  1159. return static::sendToGateway($address, $gateway_data);
  1160. }
  1161. /**
  1162. * 将clientid数组转换成address数组
  1163. *
  1164. * @param array $client_id_array
  1165. * @return array
  1166. */
  1167. protected static function clientIdArrayToAddressArray(array $client_id_array)
  1168. {
  1169. $address_connection_array = array();
  1170. foreach ($client_id_array as $client_id) {
  1171. $address_data = Context::clientIdToAddress($client_id);
  1172. if ($address_data) {
  1173. $address = long2ip($address_data['local_ip']) .
  1174. ":{$address_data['local_port']}";
  1175. $address_connection_array[$address][$address_data['connection_id']] = $address_data['connection_id'];
  1176. }
  1177. }
  1178. return $address_connection_array;
  1179. }
  1180. /**
  1181. * 设置 gateway 实例
  1182. *
  1183. * @param \GatewayWorker\BusinessWorker $business_worker_instance
  1184. */
  1185. public static function setBusinessWorker($business_worker_instance)
  1186. {
  1187. static::$businessWorker = $business_worker_instance;
  1188. }
  1189. /**
  1190. * 获取通过注册中心获取所有 gateway 通讯地址
  1191. *
  1192. * @return array
  1193. * @throws Exception
  1194. */
  1195. protected static function getAllGatewayAddressesFromRegister()
  1196. {
  1197. static $addresses_cache, $last_update;
  1198. $time_now = time();
  1199. $expiration_time = 1;
  1200. $register_addresses = (array)static::$registerAddress;
  1201. if(empty($addresses_cache) || $time_now - $last_update > $expiration_time) {
  1202. foreach ($register_addresses as $register_address) {
  1203. set_error_handler(function(){});
  1204. $client = stream_socket_client('tcp://' . $register_address, $errno, $errmsg, static::$connectTimeout);
  1205. restore_error_handler();
  1206. if ($client) {
  1207. break;
  1208. }
  1209. }
  1210. if (!$client) {
  1211. throw new Exception('Can not connect to tcp://' . $register_address . ' ' . $errmsg);
  1212. }
  1213. fwrite($client, '{"event":"worker_connect","secret_key":"' . static::$secretKey . '"}' . "\n");
  1214. stream_set_timeout($client, 5);
  1215. $ret = fgets($client, 655350);
  1216. if (!$ret || !$data = json_decode(trim($ret), true)) {
  1217. throw new Exception('getAllGatewayAddressesFromRegister fail. tcp://' .
  1218. $register_address . ' return ' . var_export($ret, true));
  1219. }
  1220. $last_update = $time_now;
  1221. $addresses_cache = $data['addresses'];
  1222. }
  1223. if (!$addresses_cache) {
  1224. throw new Exception('Gateway::getAllGatewayAddressesFromRegister() with registerAddress:' .
  1225. json_encode(static::$registerAddress) . ' return ' . var_export($addresses_cache, true));
  1226. }
  1227. return $addresses_cache;
  1228. }
  1229. /**
  1230. * 检查群组id是否合法
  1231. *
  1232. * @param $group
  1233. * @return bool
  1234. */
  1235. protected static function isValidGroupId($group)
  1236. {
  1237. if (empty($group)) {
  1238. echo new \Exception('group('.var_export($group, true).') empty');
  1239. return false;
  1240. }
  1241. return true;
  1242. }
  1243. }
  1244. /**
  1245. * 上下文 包含当前用户uid, 内部通信local_ip local_port socket_id ,以及客户端client_ip client_port
  1246. */
  1247. class Context
  1248. {
  1249. /**
  1250. * 内部通讯id
  1251. * @var string
  1252. */
  1253. public static $local_ip;
  1254. /**
  1255. * 内部通讯端口
  1256. * @var int
  1257. */
  1258. public static $local_port;
  1259. /**
  1260. * 客户端ip
  1261. * @var string
  1262. */
  1263. public static $client_ip;
  1264. /**
  1265. * 客户端端口
  1266. * @var int
  1267. */
  1268. public static $client_port;
  1269. /**
  1270. * client_id
  1271. * @var string
  1272. */
  1273. public static $client_id;
  1274. /**
  1275. * 连接connection->id
  1276. * @var int
  1277. */
  1278. public static $connection_id;
  1279. /**
  1280. * 旧的session
  1281. *
  1282. * @var string
  1283. */
  1284. public static $old_session;
  1285. /**
  1286. * 编码session
  1287. * @param mixed $session_data
  1288. * @return string
  1289. */
  1290. public static function sessionEncode($session_data = '')
  1291. {
  1292. if($session_data !== '')
  1293. {
  1294. return serialize($session_data);
  1295. }
  1296. return '';
  1297. }
  1298. /**
  1299. * 解码session
  1300. * @param string $session_buffer
  1301. * @return mixed
  1302. */
  1303. public static function sessionDecode($session_buffer)
  1304. {
  1305. return unserialize($session_buffer);
  1306. }
  1307. /**
  1308. * 清除上下文
  1309. * @return void
  1310. */
  1311. public static function clear()
  1312. {
  1313. static::$local_ip = static::$local_port = static::$client_ip = static::$client_port =
  1314. static::$client_id = static::$connection_id = static::$old_session = null;
  1315. }
  1316. /**
  1317. * 通讯地址到client_id的转换
  1318. * @return string
  1319. */
  1320. public static function addressToClientId($local_ip, $local_port, $connection_id)
  1321. {
  1322. return bin2hex(pack('NnN', $local_ip, $local_port, $connection_id));
  1323. }
  1324. /**
  1325. * client_id到通讯地址的转换
  1326. * @return array
  1327. */
  1328. public static function clientIdToAddress($client_id)
  1329. {
  1330. if(strlen($client_id) !== 20)
  1331. {
  1332. throw new \Exception("client_id $client_id is invalid");
  1333. }
  1334. return unpack('Nlocal_ip/nlocal_port/Nconnection_id' ,pack('H*', $client_id));
  1335. }
  1336. }
  1337. /**
  1338. * Gateway 与 Worker 间通讯的二进制协议
  1339. *
  1340. * struct GatewayProtocol
  1341. * {
  1342. * unsigned int pack_len,
  1343. * unsigned char cmd,//命令字
  1344. * unsigned int local_ip,
  1345. * unsigned short local_port,
  1346. * unsigned int client_ip,
  1347. * unsigned short client_port,
  1348. * unsigned int connection_id,
  1349. * unsigned char flag,
  1350. * unsigned short gateway_port,
  1351. * unsigned int ext_len,
  1352. * char[ext_len] ext_data,
  1353. * char[pack_length-HEAD_LEN] body//包体
  1354. * }
  1355. * NCNnNnNCnN
  1356. */
  1357. class GatewayProtocol
  1358. {
  1359. // 发给worker,gateway有一个新的连接
  1360. const CMD_ON_CONNECT = 1;
  1361. // 发给worker的,客户端有消息
  1362. const CMD_ON_MESSAGE = 3;
  1363. // 发给worker上的关闭链接事件
  1364. const CMD_ON_CLOSE = 4;
  1365. // 发给gateway的向单个用户发送数据
  1366. const CMD_SEND_TO_ONE = 5;
  1367. // 发给gateway的向所有用户发送数据
  1368. const CMD_SEND_TO_ALL = 6;
  1369. // 发给gateway的踢出用户
  1370. // 1、如果有待发消息,将在发送完后立即销毁用户连接
  1371. // 2、如果无待发消息,将立即销毁用户连接
  1372. const CMD_KICK = 7;
  1373. // 发给gateway的立即销毁用户连接
  1374. const CMD_DESTROY = 8;
  1375. // 发给gateway,通知用户session更新
  1376. const CMD_UPDATE_SESSION = 9;
  1377. // 获取在线状态
  1378. const CMD_GET_ALL_CLIENT_SESSIONS = 10;
  1379. // 判断是否在线
  1380. const CMD_IS_ONLINE = 11;
  1381. // client_id绑定到uid
  1382. const CMD_BIND_UID = 12;
  1383. // 解绑
  1384. const CMD_UNBIND_UID = 13;
  1385. // 向uid发送数据
  1386. const CMD_SEND_TO_UID = 14;
  1387. // 根据uid获取绑定的clientid
  1388. const CMD_GET_CLIENT_ID_BY_UID = 15;
  1389. // 加入组
  1390. const CMD_JOIN_GROUP = 20;
  1391. // 离开组
  1392. const CMD_LEAVE_GROUP = 21;
  1393. // 向组成员发消息
  1394. const CMD_SEND_TO_GROUP = 22;
  1395. // 获取组成员
  1396. const CMD_GET_CLIENT_SESSIONS_BY_GROUP = 23;
  1397. // 获取组在线连接数
  1398. const CMD_GET_CLIENT_COUNT_BY_GROUP = 24;
  1399. // 按照条件查找
  1400. const CMD_SELECT = 25;
  1401. // 获取在线的群组ID
  1402. const CMD_GET_GROUP_ID_LIST = 26;
  1403. // 取消分组
  1404. const CMD_UNGROUP = 27;
  1405. // worker连接gateway事件
  1406. const CMD_WORKER_CONNECT = 200;
  1407. // 心跳
  1408. const CMD_PING = 201;
  1409. // GatewayClient连接gateway事件
  1410. const CMD_GATEWAY_CLIENT_CONNECT = 202;
  1411. // 根据client_id获取session
  1412. const CMD_GET_SESSION_BY_CLIENT_ID = 203;
  1413. // 发给gateway,覆盖session
  1414. const CMD_SET_SESSION = 204;
  1415. // 当websocket握手时触发,只有websocket协议支持此命令字
  1416. const CMD_ON_WEBSOCKET_CONNECT = 205;
  1417. // 包体是标量
  1418. const FLAG_BODY_IS_SCALAR = 0x01;
  1419. // 通知gateway在send时不调用协议encode方法,在广播组播时提升性能
  1420. const FLAG_NOT_CALL_ENCODE = 0x02;
  1421. /**
  1422. * 包头长度
  1423. *
  1424. * @var int
  1425. */
  1426. const HEAD_LEN = 28;
  1427. public static $empty = array(
  1428. 'cmd' => 0,
  1429. 'local_ip' => 0,
  1430. 'local_port' => 0,
  1431. 'client_ip' => 0,
  1432. 'client_port' => 0,
  1433. 'connection_id' => 0,
  1434. 'flag' => 0,
  1435. 'gateway_port' => 0,
  1436. 'ext_data' => '',
  1437. 'body' => '',
  1438. );
  1439. /**
  1440. * 返回包长度
  1441. *
  1442. * @param string $buffer
  1443. * @return int return current package length
  1444. */
  1445. public static function input($buffer)
  1446. {
  1447. if (strlen($buffer) < self::HEAD_LEN) {
  1448. return 0;
  1449. }
  1450. $data = unpack("Npack_len", $buffer);
  1451. return $data['pack_len'];
  1452. }
  1453. /**
  1454. * 获取整个包的 buffer
  1455. *
  1456. * @param mixed $data
  1457. * @return string
  1458. */
  1459. public static function encode($data)
  1460. {
  1461. $flag = (int)is_scalar($data['body']);
  1462. if (!$flag) {
  1463. $data['body'] = serialize($data['body']);
  1464. }
  1465. $data['flag'] |= $flag;
  1466. $ext_len = strlen($data['ext_data']);
  1467. $package_len = self::HEAD_LEN + $ext_len + strlen($data['body']);
  1468. return pack("NCNnNnNCnN", $package_len,
  1469. $data['cmd'], $data['local_ip'],
  1470. $data['local_port'], $data['client_ip'],
  1471. $data['client_port'], $data['connection_id'],
  1472. $data['flag'], $data['gateway_port'],
  1473. $ext_len) . $data['ext_data'] . $data['body'];
  1474. }
  1475. /**
  1476. * 从二进制数据转换为数组
  1477. *
  1478. * @param string $buffer
  1479. * @return array
  1480. */
  1481. public static function decode($buffer)
  1482. {
  1483. $data = unpack("Npack_len/Ccmd/Nlocal_ip/nlocal_port/Nclient_ip/nclient_port/Nconnection_id/Cflag/ngateway_port/Next_len",
  1484. $buffer);
  1485. if ($data['ext_len'] > 0) {
  1486. $data['ext_data'] = substr($buffer, self::HEAD_LEN, $data['ext_len']);
  1487. if ($data['flag'] & self::FLAG_BODY_IS_SCALAR) {
  1488. $data['body'] = substr($buffer, self::HEAD_LEN + $data['ext_len']);
  1489. } else {
  1490. $data['body'] = unserialize(substr($buffer, self::HEAD_LEN + $data['ext_len']));
  1491. }
  1492. } else {
  1493. $data['ext_data'] = '';
  1494. if ($data['flag'] & self::FLAG_BODY_IS_SCALAR) {
  1495. $data['body'] = substr($buffer, self::HEAD_LEN);
  1496. } else {
  1497. $data['body'] = unserialize(substr($buffer, self::HEAD_LEN));
  1498. }
  1499. }
  1500. return $data;
  1501. }
  1502. }