Gateway.php 54 KB

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