GameGateway.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. <?php
  2. /**
  3. *
  4. * 暴露给客户端的连接网关 只负责网络io
  5. * 1、监听客户端连接
  6. * 2、监听后端回应并转发回应给前端
  7. *
  8. * @author walkor <worker-man@qq.com>
  9. *
  10. */
  11. require_once WORKERMAN_ROOT_DIR . 'Core/SocketWorker.php';
  12. require_once WORKERMAN_ROOT_DIR . 'Applications/GameBuffer.php';
  13. require_once WORKERMAN_ROOT_DIR . 'Applications/Store.php';
  14. class GameGateway extends WORKERMAN\Core\SocketWorker
  15. {
  16. // 内部通信socket
  17. protected $innerMainSocket = null;
  18. // uid到连接的映射
  19. protected $uidConnMap = array();
  20. // 连接到uid的映射
  21. protected $connUidMap = array();
  22. // 到GameWorker的通信地址
  23. protected $workerAddresses = array();
  24. // 当前处理的包数据
  25. protected $data = array();
  26. public function start()
  27. {
  28. // 安装信号处理函数
  29. $this->installSignal();
  30. // 添加accept事件
  31. $ret = $this->event->add($this->mainSocket, WORKERMAN\Core\Events\BaseEvent::EV_READ, array($this, 'accept'));
  32. // 创建内部通信套接字
  33. $inner_port = posix_getpid();
  34. $lan_ip = WORKERMAN\Core\Lib\Config::get('workers.'.$this->workerName.'.lan_ip');
  35. if(!$lan_ip)
  36. {
  37. $this->notice($this->workerName.'.lan_ip not set');
  38. $lan_ip = '127.0.0.1';
  39. }
  40. $error_no = 0;
  41. $error_msg = '';
  42. $this->innerMainSocket = stream_socket_server("udp://$lan_ip:$inner_port", $error_no, $error_msg, STREAM_SERVER_BIND);
  43. if(!$this->innerMainSocket)
  44. {
  45. $this->notice('create innerMainSocket fail and exit '.$error_no . ':'.$error_msg);
  46. sleep(1);
  47. exit(0);
  48. }
  49. else
  50. {
  51. stream_set_blocking($this->innerMainSocket , 0);
  52. }
  53. $this->registerAddress("udp://$lan_ip:$inner_port");
  54. // 添加读udp事件
  55. $this->event->add($this->innerMainSocket, WORKERMAN\Core\Events\BaseEvent::EV_READ, array($this, 'recvUdp'));
  56. // 初始化到worker的通信地址
  57. $this->initWorkerAddresses();
  58. // 主体循环,整个子进程会阻塞在这个函数上
  59. $ret = $this->event->loop();
  60. $this->notice('worker loop exit');
  61. exit(0);
  62. }
  63. /**
  64. * 存储全局的通信地址
  65. * @param string $address
  66. * @todo 用锁机制等保证数据完整性
  67. */
  68. protected function registerAddress($address)
  69. {
  70. $key = 'GLOBAL_GATEWAY_ADDRESS';
  71. $addresses = Store::get($key);
  72. if(empty($addresses))
  73. {
  74. $addresses = array($address);
  75. }
  76. else
  77. {
  78. $addresses[] = $address;
  79. }
  80. Store::set($key, $addresses);
  81. }
  82. /**
  83. * 接收Udp数据
  84. * 如果数据超过一个udp包长,需要业务自己解析包体,判断数据是否全部到达
  85. * @param resource $socket
  86. * @param $null_one $flag
  87. * @param $null_two $base
  88. * @return void
  89. */
  90. public function recvUdp($socket, $null_one = null, $null_two = null)
  91. {
  92. $data = stream_socket_recvfrom($socket , self::MAX_UDP_PACKEG_SIZE, 0, $address);
  93. // 惊群效应
  94. if(false === $data || empty($address))
  95. {
  96. return false;
  97. }
  98. $this->currentClientAddress = $address;
  99. $this->innerDealProcess($data);
  100. }
  101. protected function initWorkerAddresses()
  102. {
  103. $this->workerAddresses = WORKERMAN\Core\Lib\Config::get('workers.'.$this->workerName.'.game_worker');
  104. if(!$this->workerAddresses)
  105. {
  106. $this->notice($this->workerName.'game_worker not set');
  107. }
  108. }
  109. public function dealInput($recv_str)
  110. {
  111. return GameBuffer::input($recv_str, $this->data);
  112. }
  113. public function innerDealProcess($recv_str)
  114. {
  115. $data = GameBuffer::decode($recv_str);
  116. if($data['cmd'] != GameBuffer::CMD_GATEWAY)
  117. {
  118. $this->notice('gateway inner pack err data:' .$recv_str . ' serialize:' . serialize($data) );
  119. return;
  120. }
  121. switch($data['sub_cmd'])
  122. {
  123. case GameBuffer::SCMD_SEND_DATA:
  124. return $this->sendToUid($data['to_uid'], $recv_str);
  125. case GameBuffer::SCMD_KICK_UID:
  126. return $this->closeClientByUid($data['to_uid'] );
  127. case GameBuffer::SCMD_KICK_ADDRESS:
  128. $fd = (int)trim($data['body']);
  129. $uid = $this->getUidByFd($fd);
  130. if($uid)
  131. {
  132. return $this->closeClientByUid($uid);
  133. }
  134. return;
  135. case GameBuffer::SCMD_BROADCAST:
  136. return $this->broadCast($recv_str);
  137. case GameBuffer::SCMD_CONNECT_SUCCESS:
  138. $socket_id = $data['from_uid'];
  139. $uid = $data['to_uid'];
  140. // 查看是否已经绑定uid
  141. $binded_uid = $this->getUidByFd($socket_id);
  142. if($binded_uid)
  143. {
  144. $this->notice('notify connection success fail ' . $socket_id . ' already binded data:'.serialize($data));
  145. return;
  146. }
  147. $this->uidConnMap[$uid] = $socket_id;
  148. $this->connections[$socket_id] = $uid;
  149. }
  150. }
  151. protected function broadCast($bin_data)
  152. {
  153. foreach($this->uidConnMap as $uid=>$conn)
  154. {
  155. $this->sendToUid($uid, $bin_data);
  156. }
  157. }
  158. public function closeClientByUid($uid)
  159. {
  160. $fd = $this->getFdByUid($uid);
  161. if($fd)
  162. {
  163. unset($this->uidConnMap[$uid], $this->connUidMap[$fd]);
  164. parent::closeClient($fd);
  165. }
  166. }
  167. protected function getFdByUid($uid)
  168. {
  169. if(isset($this->uidConnMap[$uid]))
  170. {
  171. return $this->uidConnMap[$uid];
  172. }
  173. return 0;
  174. }
  175. protected function getUidByFd($fd)
  176. {
  177. if(isset($this->connUidMap[$fd]))
  178. {
  179. return $this->connUidMap[$fd];
  180. }
  181. return 0;
  182. }
  183. public function sendToUid($uid, $bin_data)
  184. {
  185. if(!isset($this->uidConnMap[$uid]))
  186. {
  187. return false;
  188. }
  189. $send_len = fwrite($this->connections[$this->uidConnMap[$uid]], $bin_data);
  190. return $send_len == strlen($bin_data);
  191. }
  192. public function dealProcess($recv_str)
  193. {
  194. // 判断用户是否认证过
  195. $from_uid = $this->getUidByFd($this->currentDealFd);
  196. if(!$from_uid)
  197. {
  198. // 没传sid
  199. if(empty($this->data['body']))
  200. {
  201. $this->notice("onConnect miss sid ip:".$this->getRemoteIp(). " data[".serialize($this->data)."]");
  202. $this->closeClient($this->currentDealFd);
  203. return;
  204. }
  205. // 发送onconnet事件包,包体是sid
  206. $on_buffer = new GameBuffer();
  207. $on_buffer->header['cmd'] = GameBuffer::CMD_SYSTEM;
  208. $on_buffer->header['sub_cmd'] = GameBuffer::SCMD_ON_CONNECT;
  209. // 用from_uid来临时存储socketid
  210. $on_buffer->header['from_uid'] = $this->currentDealFd;
  211. $on_buffer->body = $this->data['body'];
  212. $this->sendToWorker($on_buffer->getBuffer());
  213. return;
  214. }
  215. // 认证过
  216. $this->fillFromUid($recv_str, $from_uid);
  217. $this->sendToWorker($recv_str);
  218. }
  219. // 讲协议的from_uid填充为正确的值
  220. protected function fillFromUid(&$bin_data, $from_uid)
  221. {
  222. // from_uid在包头的12-15字节
  223. $bin_data = substr_replace($bin_data, pack('I', $from_uid), 11, 4);
  224. }
  225. protected function sendToWorker($bin_data)
  226. {
  227. $client = stream_socket_client($this->workerAddresses[array_rand($this->workerAddresses)]);
  228. $len = stream_socket_sendto($client, $bin_data);
  229. return $len == strlen($bin_data);
  230. }
  231. protected function notice($str, $display=true)
  232. {
  233. $str = 'Worker['.get_class($this).']:'."$str ip:".$this->getRemoteIp();
  234. WORKERMAN\Core\Lib\Log::add($str);
  235. if($display && WORKERMAN\Core\Lib\Config::get('debug') == 1)
  236. {
  237. echo $str."\n";
  238. }
  239. }
  240. }