Gateway.php 9.2 KB

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