Gateway.php 49 KB

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