12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604 |
- <?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 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;
- $time_now = time();
- $expiration_time = 1;
- $register_addresses = (array)static::$registerAddress;
- 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;
- }
- }
|