GameGateway.php 8.5 KB

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