Gateway.php 9.1 KB

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