Gateway.php 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604
  1. <?php
  2. namespace GatewayClient;
  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. if(empty($addresses_cache) || $time_now - $last_update > $expiration_time) {
  1204. foreach ($register_addresses as $register_address) {
  1205. set_error_handler(function(){});
  1206. $client = stream_socket_client('tcp://' . $register_address, $errno, $errmsg, static::$connectTimeout);
  1207. restore_error_handler();
  1208. if ($client) {
  1209. break;
  1210. }
  1211. }
  1212. if (!$client) {
  1213. throw new Exception('Can not connect to tcp://' . $register_address . ' ' . $errmsg);
  1214. }
  1215. fwrite($client, '{"event":"worker_connect","secret_key":"' . static::$secretKey . '"}' . "\n");
  1216. stream_set_timeout($client, 5);
  1217. $ret = fgets($client, 655350);
  1218. if (!$ret || !$data = json_decode(trim($ret), true)) {
  1219. throw new Exception('getAllGatewayAddressesFromRegister fail. tcp://' .
  1220. $register_address . ' return ' . var_export($ret, true));
  1221. }
  1222. $last_update = $time_now;
  1223. $addresses_cache = $data['addresses'];
  1224. }
  1225. if (!$addresses_cache) {
  1226. throw new Exception('Gateway::getAllGatewayAddressesFromRegister() with registerAddress:' .
  1227. json_encode(static::$registerAddress) . ' return ' . var_export($addresses_cache, true));
  1228. }
  1229. return $addresses_cache;
  1230. }
  1231. /**
  1232. * 检查群组id是否合法
  1233. *
  1234. * @param $group
  1235. * @return bool
  1236. */
  1237. protected static function isValidGroupId($group)
  1238. {
  1239. if (empty($group)) {
  1240. echo new \Exception('group('.var_export($group, true).') empty');
  1241. return false;
  1242. }
  1243. return true;
  1244. }
  1245. }
  1246. /**
  1247. * 上下文 包含当前用户uid, 内部通信local_ip local_port socket_id ,以及客户端client_ip client_port
  1248. */
  1249. class Context
  1250. {
  1251. /**
  1252. * 内部通讯id
  1253. * @var string
  1254. */
  1255. public static $local_ip;
  1256. /**
  1257. * 内部通讯端口
  1258. * @var int
  1259. */
  1260. public static $local_port;
  1261. /**
  1262. * 客户端ip
  1263. * @var string
  1264. */
  1265. public static $client_ip;
  1266. /**
  1267. * 客户端端口
  1268. * @var int
  1269. */
  1270. public static $client_port;
  1271. /**
  1272. * client_id
  1273. * @var string
  1274. */
  1275. public static $client_id;
  1276. /**
  1277. * 连接connection->id
  1278. * @var int
  1279. */
  1280. public static $connection_id;
  1281. /**
  1282. * 旧的session
  1283. *
  1284. * @var string
  1285. */
  1286. public static $old_session;
  1287. /**
  1288. * 编码session
  1289. * @param mixed $session_data
  1290. * @return string
  1291. */
  1292. public static function sessionEncode($session_data = '')
  1293. {
  1294. if($session_data !== '')
  1295. {
  1296. return serialize($session_data);
  1297. }
  1298. return '';
  1299. }
  1300. /**
  1301. * 解码session
  1302. * @param string $session_buffer
  1303. * @return mixed
  1304. */
  1305. public static function sessionDecode($session_buffer)
  1306. {
  1307. return unserialize($session_buffer);
  1308. }
  1309. /**
  1310. * 清除上下文
  1311. * @return void
  1312. */
  1313. public static function clear()
  1314. {
  1315. static::$local_ip = static::$local_port = static::$client_ip = static::$client_port =
  1316. static::$client_id = static::$connection_id = static::$old_session = null;
  1317. }
  1318. /**
  1319. * 通讯地址到client_id的转换
  1320. * @return string
  1321. */
  1322. public static function addressToClientId($local_ip, $local_port, $connection_id)
  1323. {
  1324. return bin2hex(pack('NnN', $local_ip, $local_port, $connection_id));
  1325. }
  1326. /**
  1327. * client_id到通讯地址的转换
  1328. * @return array
  1329. */
  1330. public static function clientIdToAddress($client_id)
  1331. {
  1332. if(strlen($client_id) !== 20)
  1333. {
  1334. throw new \Exception("client_id $client_id is invalid");
  1335. }
  1336. return unpack('Nlocal_ip/nlocal_port/Nconnection_id' ,pack('H*', $client_id));
  1337. }
  1338. }
  1339. /**
  1340. * Gateway 与 Worker 间通讯的二进制协议
  1341. *
  1342. * struct GatewayProtocol
  1343. * {
  1344. * unsigned int pack_len,
  1345. * unsigned char cmd,//命令字
  1346. * unsigned int local_ip,
  1347. * unsigned short local_port,
  1348. * unsigned int client_ip,
  1349. * unsigned short client_port,
  1350. * unsigned int connection_id,
  1351. * unsigned char flag,
  1352. * unsigned short gateway_port,
  1353. * unsigned int ext_len,
  1354. * char[ext_len] ext_data,
  1355. * char[pack_length-HEAD_LEN] body//包体
  1356. * }
  1357. * NCNnNnNCnN
  1358. */
  1359. class GatewayProtocol
  1360. {
  1361. // 发给worker,gateway有一个新的连接
  1362. const CMD_ON_CONNECT = 1;
  1363. // 发给worker的,客户端有消息
  1364. const CMD_ON_MESSAGE = 3;
  1365. // 发给worker上的关闭链接事件
  1366. const CMD_ON_CLOSE = 4;
  1367. // 发给gateway的向单个用户发送数据
  1368. const CMD_SEND_TO_ONE = 5;
  1369. // 发给gateway的向所有用户发送数据
  1370. const CMD_SEND_TO_ALL = 6;
  1371. // 发给gateway的踢出用户
  1372. // 1、如果有待发消息,将在发送完后立即销毁用户连接
  1373. // 2、如果无待发消息,将立即销毁用户连接
  1374. const CMD_KICK = 7;
  1375. // 发给gateway的立即销毁用户连接
  1376. const CMD_DESTROY = 8;
  1377. // 发给gateway,通知用户session更新
  1378. const CMD_UPDATE_SESSION = 9;
  1379. // 获取在线状态
  1380. const CMD_GET_ALL_CLIENT_SESSIONS = 10;
  1381. // 判断是否在线
  1382. const CMD_IS_ONLINE = 11;
  1383. // client_id绑定到uid
  1384. const CMD_BIND_UID = 12;
  1385. // 解绑
  1386. const CMD_UNBIND_UID = 13;
  1387. // 向uid发送数据
  1388. const CMD_SEND_TO_UID = 14;
  1389. // 根据uid获取绑定的clientid
  1390. const CMD_GET_CLIENT_ID_BY_UID = 15;
  1391. // 加入组
  1392. const CMD_JOIN_GROUP = 20;
  1393. // 离开组
  1394. const CMD_LEAVE_GROUP = 21;
  1395. // 向组成员发消息
  1396. const CMD_SEND_TO_GROUP = 22;
  1397. // 获取组成员
  1398. const CMD_GET_CLIENT_SESSIONS_BY_GROUP = 23;
  1399. // 获取组在线连接数
  1400. const CMD_GET_CLIENT_COUNT_BY_GROUP = 24;
  1401. // 按照条件查找
  1402. const CMD_SELECT = 25;
  1403. // 获取在线的群组ID
  1404. const CMD_GET_GROUP_ID_LIST = 26;
  1405. // 取消分组
  1406. const CMD_UNGROUP = 27;
  1407. // worker连接gateway事件
  1408. const CMD_WORKER_CONNECT = 200;
  1409. // 心跳
  1410. const CMD_PING = 201;
  1411. // GatewayClient连接gateway事件
  1412. const CMD_GATEWAY_CLIENT_CONNECT = 202;
  1413. // 根据client_id获取session
  1414. const CMD_GET_SESSION_BY_CLIENT_ID = 203;
  1415. // 发给gateway,覆盖session
  1416. const CMD_SET_SESSION = 204;
  1417. // 当websocket握手时触发,只有websocket协议支持此命令字
  1418. const CMD_ON_WEBSOCKET_CONNECT = 205;
  1419. // 包体是标量
  1420. const FLAG_BODY_IS_SCALAR = 0x01;
  1421. // 通知gateway在send时不调用协议encode方法,在广播组播时提升性能
  1422. const FLAG_NOT_CALL_ENCODE = 0x02;
  1423. /**
  1424. * 包头长度
  1425. *
  1426. * @var int
  1427. */
  1428. const HEAD_LEN = 28;
  1429. public static $empty = array(
  1430. 'cmd' => 0,
  1431. 'local_ip' => 0,
  1432. 'local_port' => 0,
  1433. 'client_ip' => 0,
  1434. 'client_port' => 0,
  1435. 'connection_id' => 0,
  1436. 'flag' => 0,
  1437. 'gateway_port' => 0,
  1438. 'ext_data' => '',
  1439. 'body' => '',
  1440. );
  1441. /**
  1442. * 返回包长度
  1443. *
  1444. * @param string $buffer
  1445. * @return int return current package length
  1446. */
  1447. public static function input($buffer)
  1448. {
  1449. if (strlen($buffer) < self::HEAD_LEN) {
  1450. return 0;
  1451. }
  1452. $data = unpack("Npack_len", $buffer);
  1453. return $data['pack_len'];
  1454. }
  1455. /**
  1456. * 获取整个包的 buffer
  1457. *
  1458. * @param mixed $data
  1459. * @return string
  1460. */
  1461. public static function encode($data)
  1462. {
  1463. $flag = (int)is_scalar($data['body']);
  1464. if (!$flag) {
  1465. $data['body'] = serialize($data['body']);
  1466. }
  1467. $data['flag'] |= $flag;
  1468. $ext_len = strlen($data['ext_data']);
  1469. $package_len = self::HEAD_LEN + $ext_len + strlen($data['body']);
  1470. return pack("NCNnNnNCnN", $package_len,
  1471. $data['cmd'], $data['local_ip'],
  1472. $data['local_port'], $data['client_ip'],
  1473. $data['client_port'], $data['connection_id'],
  1474. $data['flag'], $data['gateway_port'],
  1475. $ext_len) . $data['ext_data'] . $data['body'];
  1476. }
  1477. /**
  1478. * 从二进制数据转换为数组
  1479. *
  1480. * @param string $buffer
  1481. * @return array
  1482. */
  1483. public static function decode($buffer)
  1484. {
  1485. $data = unpack("Npack_len/Ccmd/Nlocal_ip/nlocal_port/Nclient_ip/nclient_port/Nconnection_id/Cflag/ngateway_port/Next_len",
  1486. $buffer);
  1487. if ($data['ext_len'] > 0) {
  1488. $data['ext_data'] = substr($buffer, self::HEAD_LEN, $data['ext_len']);
  1489. if ($data['flag'] & self::FLAG_BODY_IS_SCALAR) {
  1490. $data['body'] = substr($buffer, self::HEAD_LEN + $data['ext_len']);
  1491. } else {
  1492. $data['body'] = unserialize(substr($buffer, self::HEAD_LEN + $data['ext_len']));
  1493. }
  1494. } else {
  1495. $data['ext_data'] = '';
  1496. if ($data['flag'] & self::FLAG_BODY_IS_SCALAR) {
  1497. $data['body'] = substr($buffer, self::HEAD_LEN);
  1498. } else {
  1499. $data['body'] = unserialize(substr($buffer, self::HEAD_LEN));
  1500. }
  1501. }
  1502. return $data;
  1503. }
  1504. }