Gateway.php 10 KB

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