123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614 |
- <?php
- namespace GatewayClient;
- use \Exception;
- class Gateway
- {
-
- protected static $businessWorker = null;
-
- public static $registerAddress = '127.0.0.1:1236';
-
- public static $secretKey = '';
-
- public static $connectTimeout = 3;
-
- public static $persistentConnection = false;
-
- public static $addressesCacheDisable = false;
-
-
- public static function sendToAll($message, $client_id_array = null, $exclude_client_id = null, $raw = false)
- {
- $gateway_data = GatewayProtocol::$empty;
- $gateway_data['cmd'] = GatewayProtocol::CMD_SEND_TO_ALL;
- $gateway_data['body'] = $message;
- if ($raw) {
- $gateway_data['flag'] |= GatewayProtocol::FLAG_NOT_CALL_ENCODE;
- }
- if ($exclude_client_id) {
- if (!is_array($exclude_client_id)) {
- $exclude_client_id = array($exclude_client_id);
- }
- if ($client_id_array) {
- $exclude_client_id = array_flip($exclude_client_id);
- }
- }
- if ($client_id_array) {
- if (!is_array($client_id_array)) {
- echo new \Exception('bad $client_id_array:'.var_export($client_id_array, true));
- return;
- }
- $data_array = array();
- foreach ($client_id_array as $client_id) {
- if (isset($exclude_client_id[$client_id])) {
- continue;
- }
- $address = Context::clientIdToAddress($client_id);
- if ($address) {
- $key = long2ip($address['local_ip']) . ":{$address['local_port']}";
- $data_array[$key][$address['connection_id']] = $address['connection_id'];
- }
- }
- foreach ($data_array as $addr => $connection_id_list) {
- $the_gateway_data = $gateway_data;
- $the_gateway_data['ext_data'] = json_encode(array('connections' => $connection_id_list));
- static::sendToGateway($addr, $the_gateway_data);
- }
- return;
- } elseif (empty($client_id_array) && is_array($client_id_array)) {
- return;
- }
- if (!$exclude_client_id) {
- return static::sendToAllGateway($gateway_data);
- }
- $address_connection_array = static::clientIdArrayToAddressArray($exclude_client_id);
-
- if (static::$businessWorker) {
- foreach (static::$businessWorker->gatewayConnections as $address => $gateway_connection) {
- $gateway_data['ext_data'] = isset($address_connection_array[$address]) ?
- json_encode(array('exclude'=> $address_connection_array[$address])) : '';
-
- $gateway_connection->send($gateway_data);
- }
- }
- else {
- $all_addresses = static::getAllGatewayAddressesFromRegister();
- foreach ($all_addresses as $address) {
- $gateway_data['ext_data'] = isset($address_connection_array[$address]) ?
- json_encode(array('exclude'=> $address_connection_array[$address])) : '';
- static::sendToGateway($address, $gateway_data);
- }
- }
- }
-
- public static function sendToClient($client_id, $message)
- {
- return static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_SEND_TO_ONE, $message);
- }
-
- public static function isUidOnline($uid)
- {
- return (int)static::getClientIdByUid($uid);
- }
-
-
- public static function isOnline($client_id)
- {
- $address_data = Context::clientIdToAddress($client_id);
- if (!$address_data) {
- return 0;
- }
- $address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
- if (isset(static::$businessWorker)) {
- if (!isset(static::$businessWorker->gatewayConnections[$address])) {
- return 0;
- }
- }
- $gateway_data = GatewayProtocol::$empty;
- $gateway_data['cmd'] = GatewayProtocol::CMD_IS_ONLINE;
- $gateway_data['connection_id'] = $address_data['connection_id'];
- return (int)static::sendAndRecv($address, $gateway_data);
- }
-
- public static function getAllClientInfo($group = '')
- {
- echo "Warning: Gateway::getAllClientInfo is deprecated and will be removed in a future, please use Gateway::getAllClientSessions instead.";
- return static::getAllClientSessions($group);
- }
-
- public static function getAllClientSessions($group = '')
- {
- $gateway_data = GatewayProtocol::$empty;
- if (!$group) {
- $gateway_data['cmd'] = GatewayProtocol::CMD_GET_ALL_CLIENT_SESSIONS;
- } else {
- $gateway_data['cmd'] = GatewayProtocol::CMD_GET_CLIENT_SESSIONS_BY_GROUP;
- $gateway_data['ext_data'] = $group;
- }
- $status_data = array();
- $all_buffer_array = static::getBufferFromAllGateway($gateway_data);
- foreach ($all_buffer_array as $local_ip => $buffer_array) {
- foreach ($buffer_array as $local_port => $data) {
- if ($data) {
- foreach ($data as $connection_id => $session_buffer) {
- $client_id = Context::addressToClientId($local_ip, $local_port, $connection_id);
- if ($client_id === Context::$client_id) {
- $status_data[$client_id] = (array)$_SESSION;
- } else {
- $status_data[$client_id] = $session_buffer ? Context::sessionDecode($session_buffer) : array();
- }
- }
- }
- }
- }
- return $status_data;
- }
-
- public static function getClientInfoByGroup($group)
- {
- echo "Warning: Gateway::getClientInfoByGroup is deprecated and will be removed in a future, please use Gateway::getClientSessionsByGroup instead.";
- return static::getAllClientSessions($group);
- }
-
- public static function getClientSessionsByGroup($group)
- {
- if (static::isValidGroupId($group)) {
- return static::getAllClientSessions($group);
- }
- return array();
- }
-
- public static function getAllClientIdCount()
- {
- return static::getClientCountByGroup();
- }
-
- public static function getAllClientCount()
- {
- return static::getAllClientIdCount();
- }
-
- public static function getClientIdCountByGroup($group = '')
- {
- $gateway_data = GatewayProtocol::$empty;
- $gateway_data['cmd'] = GatewayProtocol::CMD_GET_CLIENT_COUNT_BY_GROUP;
- $gateway_data['ext_data'] = $group;
- $total_count = 0;
- $all_buffer_array = static::getBufferFromAllGateway($gateway_data);
- foreach ($all_buffer_array as $local_ip => $buffer_array) {
- foreach ($buffer_array as $local_port => $count) {
- if ($count) {
- $total_count += $count;
- }
- }
- }
- return $total_count;
- }
-
- public static function getClientCountByGroup($group = '')
- {
- return static::getClientIdCountByGroup($group);
- }
-
- public static function getClientIdListByGroup($group)
- {
- if (!static::isValidGroupId($group)) {
- return array();
- }
- $data = static::select(array('uid'), array('groups' => is_array($group) ? $group : array($group)));
- $client_id_map = array();
- foreach ($data as $local_ip => $buffer_array) {
- foreach ($buffer_array as $local_port => $items) {
-
- foreach ($items as $connection_id => $info) {
- $client_id = Context::addressToClientId($local_ip, $local_port, $connection_id);
- $client_id_map[$client_id] = $client_id;
- }
- }
- }
- return $client_id_map;
- }
-
- public static function getAllClientIdList()
- {
- return static::formatClientIdFromGatewayBuffer(static::select(array('uid')));
- }
-
- protected static function formatClientIdFromGatewayBuffer($data)
- {
- $client_id_list = array();
- foreach ($data as $local_ip => $buffer_array) {
- foreach ($buffer_array as $local_port => $items) {
-
- foreach ($items as $connection_id => $info) {
- $client_id = Context::addressToClientId($local_ip, $local_port, $connection_id);
- $client_id_list[$client_id] = $client_id;
- }
- }
- }
- return $client_id_list;
- }
-
- public static function getClientIdByUid($uid)
- {
- $gateway_data = GatewayProtocol::$empty;
- $gateway_data['cmd'] = GatewayProtocol::CMD_GET_CLIENT_ID_BY_UID;
- $gateway_data['ext_data'] = $uid;
- $client_list = array();
- $all_buffer_array = static::getBufferFromAllGateway($gateway_data);
- foreach ($all_buffer_array as $local_ip => $buffer_array) {
- foreach ($buffer_array as $local_port => $connection_id_array) {
- if ($connection_id_array) {
- foreach ($connection_id_array as $connection_id) {
- $client_list[] = Context::addressToClientId($local_ip, $local_port, $connection_id);
- }
- }
- }
- }
- return $client_list;
- }
-
- public static function getUidListByGroup($group)
- {
- if (!static::isValidGroupId($group)) {
- return array();
- }
- $group = is_array($group) ? $group : array($group);
- $data = static::select(array('uid'), array('groups' => $group));
- $uid_map = array();
- foreach ($data as $local_ip => $buffer_array) {
- foreach ($buffer_array as $local_port => $items) {
-
- foreach ($items as $connection_id => $info) {
- if (!empty($info['uid'])) {
- $uid_map[$info['uid']] = $info['uid'];
- }
- }
- }
- }
- return $uid_map;
- }
-
- public static function getUidCountByGroup($group)
- {
- if (static::isValidGroupId($group)) {
- return count(static::getUidListByGroup($group));
- }
- return 0;
- }
-
- public static function getAllUidList()
- {
- $data = static::select(array('uid'));
- $uid_map = array();
- foreach ($data as $local_ip => $buffer_array) {
- foreach ($buffer_array as $local_port => $items) {
-
- foreach ($items as $connection_id => $info) {
- if (!empty($info['uid'])) {
- $uid_map[$info['uid']] = $info['uid'];
- }
- }
- }
- }
- return $uid_map;
- }
-
- public static function getAllUidCount()
- {
- return count(static::getAllUidList());
- }
-
- public static function getUidByClientId($client_id)
- {
- $data = static::select(array('uid'), array('client_id'=>array($client_id)));
- foreach ($data as $local_ip => $buffer_array) {
- foreach ($buffer_array as $local_port => $items) {
-
- foreach ($items as $info) {
- return $info['uid'];
- }
- }
- }
- }
-
- public static function getAllGroupIdList()
- {
- $gateway_data = GatewayProtocol::$empty;
- $gateway_data['cmd'] = GatewayProtocol::CMD_GET_GROUP_ID_LIST;
- $group_id_list = array();
- $all_buffer_array = static::getBufferFromAllGateway($gateway_data);
- foreach ($all_buffer_array as $local_ip => $buffer_array) {
- foreach ($buffer_array as $local_port => $group_id_array) {
- if (is_array($group_id_array)) {
- foreach ($group_id_array as $group_id) {
- if (!isset($group_id_list[$group_id])) {
- $group_id_list[$group_id] = $group_id;
- }
- }
- }
- }
- }
- return $group_id_list;
- }
-
- public static function getAllGroupUidCount()
- {
- $group_uid_map = static::getAllGroupUidList();
- $group_uid_count_map = array();
- foreach ($group_uid_map as $group_id => $uid_list) {
- $group_uid_count_map[$group_id] = count($uid_list);
- }
- return $group_uid_count_map;
- }
-
- public static function getAllGroupUidList()
- {
- $data = static::select(array('uid','groups'));
- $group_uid_map = array();
- foreach ($data as $local_ip => $buffer_array) {
- foreach ($buffer_array as $local_port => $items) {
-
- foreach ($items as $connection_id => $info) {
- if (empty($info['uid']) || empty($info['groups'])) {
- break;
- }
- $uid = $info['uid'];
- foreach ($info['groups'] as $group_id) {
- if(!isset($group_uid_map[$group_id])) {
- $group_uid_map[$group_id] = array();
- }
- $group_uid_map[$group_id][$uid] = $uid;
- }
- }
- }
- }
- return $group_uid_map;
- }
-
- public static function getAllGroupClientIdList()
- {
- $data = static::select(array('groups'));
- $group_client_id_map = array();
- foreach ($data as $local_ip => $buffer_array) {
- foreach ($buffer_array as $local_port => $items) {
-
- foreach ($items as $connection_id => $info) {
- if (empty($info['groups'])) {
- break;
- }
- $client_id = Context::addressToClientId($local_ip, $local_port, $connection_id);
- foreach ($info['groups'] as $group_id) {
- if(!isset($group_client_id_map[$group_id])) {
- $group_client_id_map[$group_id] = array();
- }
- $group_client_id_map[$group_id][$client_id] = $client_id;
- }
- }
- }
- }
- return $group_client_id_map;
- }
-
- public static function getAllGroupClientIdCount()
- {
- $group_client_map = static::getAllGroupClientIdList();
- $group_client_count_map = array();
- foreach ($group_client_map as $group_id => $client_id_list) {
- $group_client_count_map[$group_id] = count($client_id_list);
- }
- return $group_client_count_map;
- }
-
- protected static function select($fields = array('session','uid','groups'), $where = array())
- {
- $t = microtime(true);
- $gateway_data = GatewayProtocol::$empty;
- $gateway_data['cmd'] = GatewayProtocol::CMD_SELECT;
- $gateway_data['ext_data'] = array('fields' => $fields, 'where' => $where);
- $gateway_data_list = array();
-
- if (isset($where['client_id'])) {
- $client_id_list = $where['client_id'];
- unset($gateway_data['ext_data']['where']['client_id']);
- $gateway_data['ext_data']['where']['connection_id'] = array();
- foreach ($client_id_list as $client_id) {
- $address_data = Context::clientIdToAddress($client_id);
- if (!$address_data) {
- continue;
- }
- $address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
- if (!isset($gateway_data_list[$address])) {
- $gateway_data_list[$address] = $gateway_data;
- }
- $gateway_data_list[$address]['ext_data']['where']['connection_id'][$address_data['connection_id']] = $address_data['connection_id'];
- }
- foreach ($gateway_data_list as $address => $item) {
- $gateway_data_list[$address]['ext_data'] = json_encode($item['ext_data']);
- }
-
- if (count($where) !== 1) {
- $gateway_data['ext_data'] = json_encode($gateway_data['ext_data']);
- foreach (static::getAllGatewayAddress() as $address) {
- if (!isset($gateway_data_list[$address])) {
- $gateway_data_list[$address] = $gateway_data;
- }
- }
- }
- $data = static::getBufferFromSomeGateway($gateway_data_list);
- } else {
- $gateway_data['ext_data'] = json_encode($gateway_data['ext_data']);
- $data = static::getBufferFromAllGateway($gateway_data);
- }
- return $data;
- }
-
- protected static function generateAuthBuffer()
- {
- $gateway_data = GatewayProtocol::$empty;
- $gateway_data['cmd'] = GatewayProtocol::CMD_GATEWAY_CLIENT_CONNECT;
- $gateway_data['body'] = json_encode(array(
- 'secret_key' => static::$secretKey,
- ));
- return GatewayProtocol::encode($gateway_data);
- }
-
- protected static function getBufferFromSomeGateway($gateway_data_array)
- {
- $gateway_buffer_array = array();
- $auth_buffer = static::$secretKey ? static::generateAuthBuffer() : '';
- foreach ($gateway_data_array as $address => $gateway_data) {
- if ($auth_buffer) {
- $gateway_buffer_array[$address] = $auth_buffer.GatewayProtocol::encode($gateway_data);
- } else {
- $gateway_buffer_array[$address] = GatewayProtocol::encode($gateway_data);
- }
- }
- return static::getBufferFromGateway($gateway_buffer_array);
- }
-
- protected static function getBufferFromAllGateway($gateway_data)
- {
- $addresses = static::getAllGatewayAddress();
- $gateway_buffer_array = array();
- $gateway_buffer = GatewayProtocol::encode($gateway_data);
- $gateway_buffer = static::$secretKey ? static::generateAuthBuffer() . $gateway_buffer : $gateway_buffer;
- foreach ($addresses as $address) {
- $gateway_buffer_array[$address] = $gateway_buffer;
- }
- return static::getBufferFromGateway($gateway_buffer_array);
- }
-
- protected static function getAllGatewayAddress()
- {
- if (isset(static::$businessWorker)) {
- $addresses = static::$businessWorker->getAllGatewayAddresses();
- if (empty($addresses)) {
- throw new Exception('businessWorker::getAllGatewayAddresses return empty');
- }
- } else {
- $addresses = static::getAllGatewayAddressesFromRegister();
- if (empty($addresses)) {
- return array();
- }
- }
- return $addresses;
- }
-
- protected static function getBufferFromGateway($gateway_buffer_array)
- {
- $client_array = $status_data = $client_address_map = $receive_buffer_array = $recv_length_array = array();
-
- foreach ($gateway_buffer_array as $address => $gateway_buffer) {
- $client = stream_socket_client("tcp://$address", $errno, $errmsg, static::$connectTimeout);
- if ($client && strlen($gateway_buffer) === stream_socket_sendto($client, $gateway_buffer)) {
- $socket_id = (int)$client;
- $client_array[$socket_id] = $client;
- $client_address_map[$socket_id] = explode(':', $address);
- $receive_buffer_array[$socket_id] = '';
- }
- }
-
- $timeout = 5;
- $time_start = microtime(true);
-
- while (count($client_array) > 0) {
- $write = $except = array();
- $read = $client_array;
- if (@stream_select($read, $write, $except, $timeout)) {
- foreach ($read as $client) {
- $socket_id = (int)$client;
- $buffer = stream_socket_recvfrom($client, 65535);
- if ($buffer !== '' && $buffer !== false) {
- $receive_buffer_array[$socket_id] .= $buffer;
- $receive_length = strlen($receive_buffer_array[$socket_id]);
- if (empty($recv_length_array[$socket_id]) && $receive_length >= 4) {
- $recv_length_array[$socket_id] = current(unpack('N', $receive_buffer_array[$socket_id]));
- }
- if (!empty($recv_length_array[$socket_id]) && $receive_length >= $recv_length_array[$socket_id] + 4) {
- unset($client_array[$socket_id]);
- }
- } elseif (feof($client)) {
- unset($client_array[$socket_id]);
- }
- }
- }
- if (microtime(true) - $time_start > $timeout) {
- break;
- }
- }
- $format_buffer_array = array();
- foreach ($receive_buffer_array as $socket_id => $buffer) {
- $local_ip = ip2long($client_address_map[$socket_id][0]);
- $local_port = $client_address_map[$socket_id][1];
- $format_buffer_array[$local_ip][$local_port] = unserialize(substr($buffer, 4));
- }
- return $format_buffer_array;
- }
-
- public static function closeClient($client_id, $message = null)
- {
- if ($client_id === Context::$client_id) {
- return static::closeCurrentClient($message);
- }
- else {
- $address_data = Context::clientIdToAddress($client_id);
- if (!$address_data) {
- return false;
- }
- $address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
- return static::kickAddress($address, $address_data['connection_id'], $message);
- }
- }
-
- public static function destoryClient($client_id)
- {
- if ($client_id === Context::$client_id) {
- return static::destoryCurrentClient();
- }
- else {
- $address_data = Context::clientIdToAddress($client_id);
- if (!$address_data) {
- return false;
- }
- $address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
- return static::destroyAddress($address, $address_data['connection_id']);
- }
- }
-
- public static function destoryCurrentClient()
- {
- if (!Context::$connection_id) {
- throw new Exception('destoryCurrentClient can not be called in async context');
- }
- $address = long2ip(Context::$local_ip) . ':' . Context::$local_port;
- return static::destroyAddress($address, Context::$connection_id);
- }
-
- public static function bindUid($client_id, $uid)
- {
- static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_BIND_UID, '', $uid);
- }
-
- public static function unbindUid($client_id, $uid)
- {
- static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_UNBIND_UID, '', $uid);
- }
-
- public static function joinGroup($client_id, $group)
- {
- static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_JOIN_GROUP, '', $group);
- }
-
- public static function leaveGroup($client_id, $group)
- {
- static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_LEAVE_GROUP, '', $group);
- }
-
- public static function ungroup($group)
- {
- if (!static::isValidGroupId($group)) {
- return false;
- }
- $gateway_data = GatewayProtocol::$empty;
- $gateway_data['cmd'] = GatewayProtocol::CMD_UNGROUP;
- $gateway_data['ext_data'] = $group;
- return static::sendToAllGateway($gateway_data);
- }
-
- public static function sendToUid($uid, $message)
- {
- $gateway_data = GatewayProtocol::$empty;
- $gateway_data['cmd'] = GatewayProtocol::CMD_SEND_TO_UID;
- $gateway_data['body'] = $message;
- if (!is_array($uid)) {
- $uid = array($uid);
- }
- $gateway_data['ext_data'] = json_encode($uid);
- static::sendToAllGateway($gateway_data);
- }
-
- public static function sendToGroup($group, $message, $exclude_client_id = null, $raw = false)
- {
- if (!static::isValidGroupId($group)) {
- return false;
- }
- $gateway_data = GatewayProtocol::$empty;
- $gateway_data['cmd'] = GatewayProtocol::CMD_SEND_TO_GROUP;
- $gateway_data['body'] = $message;
- if ($raw) {
- $gateway_data['flag'] |= GatewayProtocol::FLAG_NOT_CALL_ENCODE;
- }
- if (!is_array($group)) {
- $group = array($group);
- }
-
- $default_ext_data_buffer = json_encode(array('group'=> $group, 'exclude'=> null));
- if (empty($exclude_client_id)) {
- $gateway_data['ext_data'] = $default_ext_data_buffer;
- return static::sendToAllGateway($gateway_data);
- }
-
- if (!is_array($exclude_client_id)) {
- $exclude_client_id = array($exclude_client_id);
- }
- $address_connection_array = static::clientIdArrayToAddressArray($exclude_client_id);
-
- if (static::$businessWorker) {
- foreach (static::$businessWorker->gatewayConnections as $address => $gateway_connection) {
- $gateway_data['ext_data'] = isset($address_connection_array[$address]) ?
- json_encode(array('group'=> $group, 'exclude'=> $address_connection_array[$address])) :
- $default_ext_data_buffer;
-
- $gateway_connection->send($gateway_data);
- }
- }
- else {
- $addresses = static::getAllGatewayAddressesFromRegister();
- foreach ($addresses as $address) {
- $gateway_data['ext_data'] = isset($address_connection_array[$address]) ?
- json_encode(array('group'=> $group, 'exclude'=> $address_connection_array[$address])) :
- $default_ext_data_buffer;
- static::sendToGateway($address, $gateway_data);
- }
- }
- }
-
- public static function setSocketSession($client_id, $session_str)
- {
- return static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_SET_SESSION, '', $session_str);
- }
-
- public static function setSession($client_id, array $session)
- {
- if (Context::$client_id === $client_id) {
- $_SESSION = $session;
- Context::$old_session = $_SESSION;
- }
- static::setSocketSession($client_id, Context::sessionEncode($session));
- }
-
-
- public static function updateSession($client_id, array $session)
- {
- if (Context::$client_id === $client_id) {
- $_SESSION = array_replace_recursive((array)$_SESSION, $session);
- Context::$old_session = $_SESSION;
- }
- static::sendCmdAndMessageToClient($client_id, GatewayProtocol::CMD_UPDATE_SESSION, '', Context::sessionEncode($session));
- }
-
-
- public static function getSession($client_id)
- {
- $address_data = Context::clientIdToAddress($client_id);
- if (!$address_data) {
- return false;
- }
- $address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
- if (isset(static::$businessWorker)) {
- if (!isset(static::$businessWorker->gatewayConnections[$address])) {
- return null;
- }
- }
- $gateway_data = GatewayProtocol::$empty;
- $gateway_data['cmd'] = GatewayProtocol::CMD_GET_SESSION_BY_CLIENT_ID;
- $gateway_data['connection_id'] = $address_data['connection_id'];
- return static::sendAndRecv($address, $gateway_data);
- }
-
- protected static function sendCmdAndMessageToClient($client_id, $cmd, $message, $ext_data = '')
- {
-
- if ($client_id === Context::$client_id || $client_id === null) {
- $address = long2ip(Context::$local_ip) . ':' . Context::$local_port;
- $connection_id = Context::$connection_id;
- } else {
- $address_data = Context::clientIdToAddress($client_id);
- if (!$address_data) {
- return false;
- }
- $address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
- $connection_id = $address_data['connection_id'];
- }
- $gateway_data = GatewayProtocol::$empty;
- $gateway_data['cmd'] = $cmd;
- $gateway_data['connection_id'] = $connection_id;
- $gateway_data['body'] = $message;
- if (!empty($ext_data)) {
- $gateway_data['ext_data'] = $ext_data;
- }
- return static::sendToGateway($address, $gateway_data);
- }
-
- protected static function sendAndRecv($address, $data)
- {
- $buffer = GatewayProtocol::encode($data);
- $buffer = static::$secretKey ? static::generateAuthBuffer() . $buffer : $buffer;
- $client = stream_socket_client("tcp://$address", $errno, $errmsg, static::$connectTimeout);
- if (!$client) {
- throw new Exception("can not connect to tcp://$address $errmsg");
- }
- if (strlen($buffer) === stream_socket_sendto($client, $buffer)) {
- $timeout = 5;
-
- stream_set_blocking($client, 1);
-
- stream_set_timeout($client, 1);
- $all_buffer = '';
- $time_start = microtime(true);
- $pack_len = 0;
- while (1) {
- $buf = stream_socket_recvfrom($client, 655350);
- if ($buf !== '' && $buf !== false) {
- $all_buffer .= $buf;
- } else {
- if (feof($client)) {
- throw new Exception("connection close tcp://$address");
- } elseif (microtime(true) - $time_start > $timeout) {
- break;
- }
- continue;
- }
- $recv_len = strlen($all_buffer);
- if (!$pack_len && $recv_len >= 4) {
- $pack_len= current(unpack('N', $all_buffer));
- }
-
- if (($pack_len && $recv_len >= $pack_len + 4) || microtime(true) - $time_start > $timeout) {
- break;
- }
- }
-
- return unserialize(substr($all_buffer, 4));
- } else {
- throw new Exception("sendAndRecv($address, \$bufer) fail ! Can not send data!", 502);
- }
- }
-
- protected static function sendToGateway($address, $gateway_data)
- {
- return static::sendBufferToGateway($address, GatewayProtocol::encode($gateway_data));
- }
-
- protected static function sendBufferToGateway($address, $gateway_buffer)
- {
-
- if (static::$businessWorker) {
- if (!isset(static::$businessWorker->gatewayConnections[$address])) {
- return false;
- }
- return static::$businessWorker->gatewayConnections[$address]->send($gateway_buffer, true);
- }
-
- $gateway_buffer = static::$secretKey ? static::generateAuthBuffer() . $gateway_buffer : $gateway_buffer;
- $flag = static::$persistentConnection ? STREAM_CLIENT_PERSISTENT | STREAM_CLIENT_CONNECT : STREAM_CLIENT_CONNECT;
- $client = stream_socket_client("tcp://$address", $errno, $errmsg, static::$connectTimeout, $flag);
- return strlen($gateway_buffer) == stream_socket_sendto($client, $gateway_buffer);
- }
-
- protected static function sendToAllGateway($gateway_data)
- {
- $buffer = GatewayProtocol::encode($gateway_data);
-
- if (static::$businessWorker) {
- foreach (static::$businessWorker->gatewayConnections as $gateway_connection) {
-
- $gateway_connection->send($buffer, true);
- }
- }
- else {
- $all_addresses = static::getAllGatewayAddressesFromRegister();
- foreach ($all_addresses as $address) {
- static::sendBufferToGateway($address, $buffer);
- }
- }
- }
-
- protected static function kickAddress($address, $connection_id, $message)
- {
- $gateway_data = GatewayProtocol::$empty;
- $gateway_data['cmd'] = GatewayProtocol::CMD_KICK;
- $gateway_data['connection_id'] = $connection_id;
- $gateway_data['body'] = $message;
- return static::sendToGateway($address, $gateway_data);
- }
-
- protected static function destroyAddress($address, $connection_id)
- {
- $gateway_data = GatewayProtocol::$empty;
- $gateway_data['cmd'] = GatewayProtocol::CMD_DESTROY;
- $gateway_data['connection_id'] = $connection_id;
- return static::sendToGateway($address, $gateway_data);
- }
-
- protected static function clientIdArrayToAddressArray(array $client_id_array)
- {
- $address_connection_array = array();
- foreach ($client_id_array as $client_id) {
- $address_data = Context::clientIdToAddress($client_id);
- if ($address_data) {
- $address = long2ip($address_data['local_ip']) .
- ":{$address_data['local_port']}";
- $address_connection_array[$address][$address_data['connection_id']] = $address_data['connection_id'];
- }
- }
- return $address_connection_array;
- }
-
- public static function setBusinessWorker($business_worker_instance)
- {
- static::$businessWorker = $business_worker_instance;
- }
-
- protected static function getAllGatewayAddressesFromRegister()
- {
- static $addresses_cache, $last_update;
- if (static::$addressesCacheDisable) {
- $addresses_cache = null;
- }
- $time_now = time();
- $expiration_time = 1;
- $register_addresses = (array)static::$registerAddress;
- $client = null;
- if(empty($addresses_cache) || $time_now - $last_update > $expiration_time) {
- foreach ($register_addresses as $register_address) {
- set_error_handler(function(){});
- $client = stream_socket_client('tcp://' . $register_address, $errno, $errmsg, static::$connectTimeout);
- restore_error_handler();
- if ($client) {
- break;
- }
- }
- if (!$client) {
- throw new Exception('Can not connect to tcp://' . $register_address . ' ' . $errmsg);
- }
- fwrite($client, '{"event":"worker_connect","secret_key":"' . static::$secretKey . '"}' . "\n");
- stream_set_timeout($client, 5);
- $ret = fgets($client, 655350);
- if (!$ret || !$data = json_decode(trim($ret), true)) {
- throw new Exception('getAllGatewayAddressesFromRegister fail. tcp://' .
- $register_address . ' return ' . var_export($ret, true));
- }
- $last_update = $time_now;
- $addresses_cache = $data['addresses'];
- }
- if (!$addresses_cache) {
- throw new Exception('Gateway::getAllGatewayAddressesFromRegister() with registerAddress:' .
- json_encode(static::$registerAddress) . ' return ' . var_export($addresses_cache, true));
- }
- return $addresses_cache;
- }
-
- protected static function isValidGroupId($group)
- {
- if (empty($group)) {
- echo new \Exception('group('.var_export($group, true).') empty');
- return false;
- }
- return true;
- }
- }
- class Context
- {
-
- public static $local_ip;
-
- public static $local_port;
-
- public static $client_ip;
-
- public static $client_port;
-
- public static $client_id;
-
- public static $connection_id;
-
- public static $old_session;
-
- public static function sessionEncode($session_data = '')
- {
- if($session_data !== '')
- {
- return serialize($session_data);
- }
- return '';
- }
-
- public static function sessionDecode($session_buffer)
- {
- return unserialize($session_buffer);
- }
-
- public static function clear()
- {
- static::$local_ip = static::$local_port = static::$client_ip = static::$client_port =
- static::$client_id = static::$connection_id = static::$old_session = null;
- }
-
- public static function addressToClientId($local_ip, $local_port, $connection_id)
- {
- return bin2hex(pack('NnN', $local_ip, $local_port, $connection_id));
- }
-
- public static function clientIdToAddress($client_id)
- {
- if(strlen($client_id) !== 20)
- {
- throw new \Exception("client_id $client_id is invalid");
- }
- return unpack('Nlocal_ip/nlocal_port/Nconnection_id' ,pack('H*', $client_id));
- }
- }
- class GatewayProtocol
- {
-
- const CMD_ON_CONNECT = 1;
-
- const CMD_ON_MESSAGE = 3;
-
- const CMD_ON_CLOSE = 4;
-
- const CMD_SEND_TO_ONE = 5;
-
- const CMD_SEND_TO_ALL = 6;
-
-
-
- const CMD_KICK = 7;
-
- const CMD_DESTROY = 8;
-
- const CMD_UPDATE_SESSION = 9;
-
- const CMD_GET_ALL_CLIENT_SESSIONS = 10;
-
- const CMD_IS_ONLINE = 11;
-
- const CMD_BIND_UID = 12;
-
- const CMD_UNBIND_UID = 13;
-
- const CMD_SEND_TO_UID = 14;
-
- const CMD_GET_CLIENT_ID_BY_UID = 15;
-
- const CMD_JOIN_GROUP = 20;
-
- const CMD_LEAVE_GROUP = 21;
-
- const CMD_SEND_TO_GROUP = 22;
-
- const CMD_GET_CLIENT_SESSIONS_BY_GROUP = 23;
-
- const CMD_GET_CLIENT_COUNT_BY_GROUP = 24;
-
- const CMD_SELECT = 25;
-
- const CMD_GET_GROUP_ID_LIST = 26;
-
- const CMD_UNGROUP = 27;
-
- const CMD_WORKER_CONNECT = 200;
-
- const CMD_PING = 201;
-
- const CMD_GATEWAY_CLIENT_CONNECT = 202;
-
- const CMD_GET_SESSION_BY_CLIENT_ID = 203;
-
- const CMD_SET_SESSION = 204;
-
- const CMD_ON_WEBSOCKET_CONNECT = 205;
-
- const FLAG_BODY_IS_SCALAR = 0x01;
-
- const FLAG_NOT_CALL_ENCODE = 0x02;
-
- const HEAD_LEN = 28;
- public static $empty = array(
- 'cmd' => 0,
- 'local_ip' => 0,
- 'local_port' => 0,
- 'client_ip' => 0,
- 'client_port' => 0,
- 'connection_id' => 0,
- 'flag' => 0,
- 'gateway_port' => 0,
- 'ext_data' => '',
- 'body' => '',
- );
-
- public static function input($buffer)
- {
- if (strlen($buffer) < self::HEAD_LEN) {
- return 0;
- }
- $data = unpack("Npack_len", $buffer);
- return $data['pack_len'];
- }
-
- public static function encode($data)
- {
- $flag = (int)is_scalar($data['body']);
- if (!$flag) {
- $data['body'] = serialize($data['body']);
- }
- $data['flag'] |= $flag;
- $ext_len = strlen($data['ext_data']);
- $package_len = self::HEAD_LEN + $ext_len + strlen($data['body']);
- return pack("NCNnNnNCnN", $package_len,
- $data['cmd'], $data['local_ip'],
- $data['local_port'], $data['client_ip'],
- $data['client_port'], $data['connection_id'],
- $data['flag'], $data['gateway_port'],
- $ext_len) . $data['ext_data'] . $data['body'];
- }
-
- public static function decode($buffer)
- {
- $data = unpack("Npack_len/Ccmd/Nlocal_ip/nlocal_port/Nclient_ip/nclient_port/Nconnection_id/Cflag/ngateway_port/Next_len",
- $buffer);
- if ($data['ext_len'] > 0) {
- $data['ext_data'] = substr($buffer, self::HEAD_LEN, $data['ext_len']);
- if ($data['flag'] & self::FLAG_BODY_IS_SCALAR) {
- $data['body'] = substr($buffer, self::HEAD_LEN + $data['ext_len']);
- } else {
- $data['body'] = unserialize(substr($buffer, self::HEAD_LEN + $data['ext_len']));
- }
- } else {
- $data['ext_data'] = '';
- if ($data['flag'] & self::FLAG_BODY_IS_SCALAR) {
- $data['body'] = substr($buffer, self::HEAD_LEN);
- } else {
- $data['body'] = unserialize(substr($buffer, self::HEAD_LEN));
- }
- }
- return $data;
- }
- }
|