Gateway.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. <?php
  2. namespace Lib;
  3. /**
  4. *
  5. * 数据发送相关
  6. * @author walkor <workerman.net>
  7. *
  8. */
  9. require_once __DIR__ . '/Autoloader.php';
  10. use \Protocols\GatewayProtocol;
  11. use \Lib\Store;
  12. use \Lib\Context;
  13. class Gateway
  14. {
  15. /**
  16. * gateway实例
  17. * @var object
  18. */
  19. protected static $businessWorker = null;
  20. /**
  21. * 向所有客户端(或者client_id_array指定的客户端)广播消息
  22. * @param string $message 向客户端发送的消息(可以是二进制数据)
  23. * @param array $client_id_array 客户端id数组
  24. */
  25. public static function sendToAll($message, $client_id_array = null)
  26. {
  27. $pack = new GatewayProtocol();
  28. $pack->header['cmd'] = GatewayProtocol::CMD_SEND_TO_ALL;
  29. $pack->header['local_ip'] = Context::$local_ip;
  30. $pack->header['local_port'] = Context::$local_port;
  31. $pack->header['socket_id'] = Context::$socket_id;
  32. $pack->header['client_ip'] = Context::$client_ip;
  33. $pack->header['client_port'] = Context::$client_port;
  34. $pack->header['client_id'] = Context::$client_id;
  35. $pack->body = (string)$message;
  36. if($client_id_array)
  37. {
  38. $params = array_merge(array('N*'), $client_id_array);
  39. $pack->ext_data = call_user_func_array('pack', $params);
  40. }
  41. elseif(empty($client_id_array) && is_array($client_id_array))
  42. {
  43. return;
  44. }
  45. $buffer = $pack->getBuffer();
  46. // 如果有businessWorker实例,说明运行在workerman环境中,通过businessWorker中的长连接发送数据
  47. if(self::$businessWorker)
  48. {
  49. foreach(self::$businessWorker->getGatewayConnections() as $con)
  50. {
  51. self::$businessWorker->sendToClient($buffer, $con);
  52. }
  53. }
  54. // 运行在其它环境中,使用udp向worker发送数据
  55. else
  56. {
  57. $all_addresses = Store::instance('gateway')->get('GLOBAL_GATEWAY_ADDRESS');
  58. foreach($all_addresses as $address)
  59. {
  60. self::sendToGateway($address, $buffer);
  61. }
  62. }
  63. }
  64. /**
  65. * 向某个客户端发消息
  66. * @param int $client_id 客户端通过Gateway::bindClientId($client_id)绑定的client_id
  67. * @param string $message
  68. */
  69. public static function sendToClient($clinet_id, $message)
  70. {
  71. return self::sendCmdAndMessageToClient($clinet_id, GatewayProtocol::CMD_SEND_TO_ONE, $message);
  72. }
  73. /**
  74. * 向当前客户端发送消息
  75. * @param string $message
  76. */
  77. public static function sendToCurrentClient($message)
  78. {
  79. return self::sendCmdAndMessageToClient(null, GatewayProtocol::CMD_SEND_TO_ONE, $message);
  80. }
  81. /**
  82. * 判断某个客户端是否在线
  83. * @param int $client_id
  84. * @return 0/1
  85. */
  86. public static function isOnline($client_id)
  87. {
  88. $pack = new GatewayProtocol();
  89. $pack->header['cmd'] = \Protocols\GatewayProtocol::CMD_IS_ONLINE;;
  90. $pack->header['client_id'] = $client_id;
  91. $address = Store::instance('gateway')->get($client_id);
  92. if(!$address)
  93. {
  94. return 0;
  95. }
  96. return self::sendUdpAndRecv($address['local_ip']. ':' .$address['local_port'], $pack->getBuffer());
  97. }
  98. /**
  99. * 获取在线状态,目前返回一个在线client_id数组
  100. * @return array
  101. */
  102. public static function getOnlineStatus()
  103. {
  104. $pack = new GatewayProtocol();
  105. $pack->header['cmd'] = \Protocols\GatewayProtocol::CMD_GET_ONLINE_STATUS;
  106. $buffer = $pack->getBuffer();
  107. $all_addresses = Store::instance('gateway')->get('GLOBAL_GATEWAY_ADDRESS');
  108. $client_array = $status_data = array();
  109. // 批量向所有gateway进程发送CMD_GET_ONLINE_STATUS命令
  110. foreach($all_addresses as $address)
  111. {
  112. $client = stream_socket_client("udp://$address", $errno, $errmsg);
  113. if(strlen($buffer) == stream_socket_sendto($client, $buffer))
  114. {
  115. $client_id = (int) $client;
  116. $client_array[$client_id] = $client;
  117. }
  118. }
  119. // 超时2秒
  120. $time_out = 2;
  121. $time_start = microtime(true);
  122. // 批量接收请求
  123. while(count($client_array) > 0)
  124. {
  125. $write = $except = array();
  126. $read = $client_array;
  127. if(stream_select($read, $write, $except, 1))
  128. {
  129. foreach($read as $client)
  130. {
  131. // udp
  132. if($data = json_decode(fread($client, 655350), true))
  133. {
  134. $status_data = array_merge($status_data, $data);
  135. }
  136. unset($client_array[$client]);
  137. }
  138. }
  139. if(microtime(true) - $time_start > $time_out)
  140. {
  141. break;
  142. }
  143. }
  144. return $status_data;
  145. }
  146. /**
  147. * 将某个客户端踢出
  148. * @param int $client_id
  149. * @param string $message
  150. */
  151. public static function kickClient($client_id)
  152. {
  153. if($client_id === Context::$client_id)
  154. {
  155. return self::kickCurrentClient();
  156. }
  157. // 不是发给当前用户则使用存储中的地址
  158. else
  159. {
  160. $address = Store::instance('gateway')->get($client_id);
  161. if(!$address)
  162. {
  163. return false;
  164. }
  165. return self::kickAddress($address['local_ip'], $address['local_port'], $address['socket_id']);
  166. }
  167. }
  168. /**
  169. * 踢掉当前客户端
  170. * @param string $message
  171. */
  172. public static function kickCurrentClient()
  173. {
  174. return self::kickAddress(Context::$local_ip, Context::$local_port, Context::$socket_id);
  175. }
  176. /**
  177. * 更新session,框架自动调用,开发者不要调用
  178. * @param int $client_id
  179. * @param string $session_str
  180. */
  181. public static function updateSocketSession($socket_id, $session_str)
  182. {
  183. $pack = new GatewayProtocol();
  184. $pack->header['cmd'] = GatewayProtocol::CMD_UPDATE_SESSION;
  185. $pack->header['socket_id'] = Context::$socket_id;
  186. $pack->ext_data = (string)$session_str;
  187. return self::sendToGateway(Context::$local_ip . ':' . Context::$local_port, $pack->getBuffer());
  188. }
  189. /**
  190. * 想某个用户网关发送命令和消息
  191. * @param int $client_id
  192. * @param int $cmd
  193. * @param string $message
  194. * @return boolean
  195. */
  196. protected static function sendCmdAndMessageToClient($client_id, $cmd , $message)
  197. {
  198. $pack = new GatewayProtocol();
  199. $pack->header['cmd'] = $cmd;
  200. // 如果是发给当前用户则直接获取上下文中的地址
  201. if($client_id === Context::$client_id || $client_id === null)
  202. {
  203. $pack->header['local_ip'] = Context::$local_ip;
  204. $pack->header['local_port'] = Context::$local_port;
  205. $pack->header['socket_id'] = Context::$socket_id;
  206. $pack->header['client_id'] = Context::$client_id;
  207. }
  208. // 不是发给当前用户则使用存储中的地址
  209. else
  210. {
  211. $address = Store::instance('gateway')->get($client_id);
  212. if(!$address)
  213. {
  214. return false;
  215. }
  216. $pack->header['local_ip'] = $address['local_ip'];
  217. $pack->header['local_port'] = $address['local_port'];
  218. $pack->header['socket_id'] = $address['socket_id'];
  219. $pack->header['client_id'] = $client_id;
  220. }
  221. $pack->header['client_ip'] = Context::$client_ip;
  222. $pack->header['client_port'] = Context::$client_port;
  223. $pack->body = (string)$message;
  224. return self::sendToGateway("{$pack->header['local_ip']}:{$pack->header['local_port']}", $pack->getBuffer());
  225. }
  226. /**
  227. * 发送udp数据并返回
  228. * @param int $address
  229. * @param string $message
  230. * @return boolean
  231. */
  232. protected static function sendUdpAndRecv($address , $buffer)
  233. {
  234. // 非workerman环境,使用udp发送数据
  235. $client = stream_socket_client("udp://$address", $errno, $errmsg);
  236. if(strlen($buffer) == stream_socket_sendto($client, $buffer))
  237. {
  238. // 阻塞读
  239. stream_set_blocking($client, 1);
  240. // 1秒超时
  241. stream_set_timeout($client, 1);
  242. // 读udp数据
  243. $data = fread($client, 655350);
  244. // 返回结果
  245. return json_decode($data, true);
  246. }
  247. else
  248. {
  249. throw new \Exception("sendUdpAndRecv($address, \$bufer) fail ! Can not send UDP data!", 502);
  250. }
  251. }
  252. /**
  253. * 发送数据到网关
  254. * @param string $address
  255. * @param string $buffer
  256. */
  257. protected static function sendToGateway($address, $buffer)
  258. {
  259. // 有$businessWorker说明是workerman环境,使用$businessWorker发送数据
  260. if(self::$businessWorker)
  261. {
  262. $connections = self::$businessWorker->getGatewayConnections();
  263. if(!isset($connections[$address]))
  264. {
  265. $e = new \Exception("sendToGateway($address, $buffer) fail \$connections:".json_encode($connections));
  266. return false;
  267. }
  268. return self::$businessWorker->sendToClient($buffer, $connections[$address]);
  269. }
  270. // 非workerman环境,使用udp发送数据
  271. $client = stream_socket_client("udp://$address", $errno, $errmsg);
  272. return strlen($buffer) == stream_socket_sendto($client, $buffer);
  273. }
  274. /**
  275. * 踢掉某个网关的socket
  276. * @param string $local_ip
  277. * @param int $local_port
  278. * @param int $socket_id
  279. * @param string $message
  280. * @param int $client_id
  281. */
  282. protected static function kickAddress($local_ip, $local_port, $socket_id)
  283. {
  284. $pack = new GatewayProtocol();
  285. $pack->header['cmd'] = GatewayProtocol::CMD_KICK;
  286. $pack->header['local_ip'] = $local_ip;
  287. $pack->header['local_port'] = $local_port;
  288. $pack->header['socket_id'] = $socket_id;
  289. if(null !== Context::$client_ip)
  290. {
  291. $pack->header['client_ip'] = Context::$client_ip;
  292. $pack->header['client_port'] = Context::$client_port;
  293. }
  294. $pack->header['client_id'] = 0;
  295. $pack->body = '';
  296. return self::sendToGateway("{$pack->header['local_ip']}:{$pack->header['local_port']}", $pack->getBuffer());
  297. }
  298. /**
  299. * 设置gateway实例
  300. * @param Bootstrap/Gateway $gateway_instance
  301. */
  302. public static function setBusinessWorker($business_worker_instance)
  303. {
  304. self::$businessWorker = $business_worker_instance;
  305. }
  306. }