GameGateway.php 8.8 KB

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