Gateway.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. <?php
  2. namespace GatewayWorker;
  3. use \Workerman\Worker;
  4. use \Workerman\Lib\Timer;
  5. use \Workerman\Protocols\GatewayProtocol;
  6. use \GatewayWorker\Lib\Lock;
  7. use \GatewayWorker\Lib\Store;
  8. class Gateway extends Worker
  9. {
  10. public $lanIp = '127.0.0.1';
  11. public $startPort = 2000;
  12. public $reloadable = false;
  13. public $pingInterval = 0;
  14. public $pingNotResponseLimit = 0;
  15. public $pingData = '';
  16. protected $_clientConnections = array();
  17. protected $_workerConnections = array();
  18. protected $_innerTcpWorker = null;
  19. protected $_innerUdpWorker = null;
  20. public function __construct($socket_name, $context_option = array())
  21. {
  22. $this->onWorkerStart = array($this, 'onWorkerStart');
  23. $this->onConnect = array($this, 'onClientConnect');
  24. $this->onMessage = array($this, 'onClientMessage');
  25. $this->onClose = array($this, 'onClientClose');
  26. $this->onWorkerStop = array($this, 'onWorkerStop');
  27. parent::__construct($socket_name, $context_option);
  28. $backrace = debug_backtrace();
  29. $this->_appInitPath = dirname($backrace[0]['file']);
  30. }
  31. public function onClientMessage($connection, $data)
  32. {
  33. $connection->pingNotResponseCount = 0;
  34. $this->sendToWorker(GatewayProtocol::CMD_ON_MESSAGE, $connection, $data);
  35. }
  36. public function onClientConnect($connection)
  37. {
  38. $connection->globalClientId = $this->createGlobalClientId();
  39. $connection->gatewayHeader = array(
  40. 'local_ip' => $this->lanIp,
  41. 'local_port' => $this->lanPort,
  42. 'client_ip'=>$connection->getRemoteIp(),
  43. 'client_port'=>$connection->getRemotePort(),
  44. 'client_id'=>$connection->globalClientId,
  45. );
  46. $connection->session = '';
  47. $connection->pingNotResponseCount = 0;
  48. $this->_clientConnections[$connection->globalClientId] = $connection;
  49. $address = $this->lanIp.':'.$this->lanPort;
  50. $this->storeClientAddress($connection->globalClientId, $address);
  51. if(method_exists('Event','onConnect'))
  52. {
  53. $this->sendToWorker(GatewayProtocol::CMD_ON_CONNECTION, $connection);
  54. }
  55. }
  56. protected function sendToWorker($cmd, $connection, $body = '')
  57. {
  58. $gateway_data = $connection->gatewayHeader;
  59. $gateway_data['cmd'] = $cmd;
  60. $gateway_data['body'] = $body;
  61. $gateway_data['ext_data'] = $connection->session;
  62. $key = array_rand($this->_workerConnections);
  63. if($key)
  64. {
  65. if(false === $this->_workerConnections[$key]->send($gateway_data))
  66. {
  67. $msg = "sendBufferToWorker fail. May be the send buffer are overflow";
  68. $this->log($msg);
  69. return false;
  70. }
  71. }
  72. else
  73. {
  74. $msg = "endBufferToWorker fail. the connections between Gateway and BusinessWorker are not ready";
  75. $this->log($msg);
  76. return false;
  77. }
  78. return true;
  79. }
  80. /**
  81. * @param int $global_client_id
  82. * @param string $address
  83. */
  84. protected function storeClientAddress($global_client_id, $address)
  85. {
  86. if(!Store::instance('gateway')->set('gateway-'.$global_client_id, $address))
  87. {
  88. $msg = 'storeClientAddress fail.';
  89. if(get_class(Store::instance('gateway')) == 'Memcached')
  90. {
  91. $msg .= " reason :".Store::instance('gateway')->getResultMessage();
  92. }
  93. $this->log($msg);
  94. return false;
  95. }
  96. return true;
  97. }
  98. protected function delClientAddress($global_client_id)
  99. {
  100. Store::instance('gateway')->delete('gateway-'.$global_client_id);
  101. }
  102. public function onClientClose($connection)
  103. {
  104. $this->sendToWorker(GatewayProtocol::CMD_ON_CLOSE, $connection);
  105. $this->delClientAddress($connection->globalClientId);
  106. unset($this->_clientConnections[$connection->globalClientId]);
  107. }
  108. protected function createGlobalClientId()
  109. {
  110. $global_socket_key = 'GLOBAL_SOCKET_ID_KEY';
  111. $store = Store::instance('gateway');
  112. $global_client_id = $store->increment($global_socket_key);
  113. if(!$global_client_id || $global_client_id > 2147483646)
  114. {
  115. $store->set($global_socket_key, 0);
  116. $global_client_id = $store->increment($global_socket_key);
  117. }
  118. if(!$global_client_id)
  119. {
  120. $msg .= "createGlobalClientId fail :";
  121. if(get_class($store) == 'Memcached')
  122. {
  123. $msg .= $store->getResultMessage();
  124. }
  125. $this->log($msg);
  126. }
  127. return $global_client_id;
  128. }
  129. public function onWorkerStart()
  130. {
  131. $this->lanPort = $this->startPort - posix_getppid() + posix_getpid();
  132. if($this->lanPort<0 || $this->lanPort >=65535)
  133. {
  134. $this->lanPort = rand($this->startPort, 65535);
  135. }
  136. if($this->pingInterval > 0)
  137. {
  138. Timer::add($this->pingInterval, array($this, 'ping'));
  139. }
  140. $this->_innerTcpWorker = new Worker("GatewayProtocol://{$this->lanIp}:{$this->lanPort}");
  141. $this->_innerTcpWorker->listen();
  142. $this->_innerUdpWorker = new Worker("GatewayProtocol://{$this->lanIp}:{$this->lanPort}");
  143. $this->_innerUdpWorker->transport = 'udp';
  144. $this->_innerUdpWorker->listen();
  145. $this->_innerTcpWorker->onMessage = array($this, 'onWorkerMessage');
  146. $this->_innerUdpWorker->onMessage = array($this, 'onWorkerMessage');
  147. $this->_innerTcpWorker->onConnect = array($this, 'onWorkerConnect');
  148. $this->_innerTcpWorker->onClose = array($this, 'onWorkerClose');
  149. if(!$this->registerAddress())
  150. {
  151. $this->log('registerAddress fail and exit');
  152. Worker::stopAll();
  153. }
  154. }
  155. public function onWorkerConnect($connection)
  156. {
  157. $connection->remoteAddress = $connection->getRemoteIp().':'.$connection->getRemotePort();
  158. $this->_workerConnections[$connection->remoteAddress] = $connection;
  159. }
  160. public function onWorkerMessage($connection, $data)
  161. {
  162. $cmd = $data['cmd'];
  163. switch($cmd)
  164. {
  165. // 向某客户端发送数据
  166. case GatewayProtocol::CMD_SEND_TO_ONE:
  167. if(isset($this->_clientConnections[$data['client_id']]))
  168. {
  169. $this->_clientConnections[$data['client_id']]->send($data['body']);
  170. }
  171. break;
  172. case GatewayProtocol::CMD_KICK:
  173. if(isset($this->_clientConnections[$data['client_id']]))
  174. {
  175. $this->_clientConnections[$data['client_id']]->close();
  176. }
  177. break;
  178. case GatewayProtocol::CMD_SEND_TO_ALL:
  179. if($data['ext_data'])
  180. {
  181. $client_id_array = unpack('N*', $data['ext_data']);
  182. foreach($client_id_array as $client_id)
  183. {
  184. if(isset($this->_clientConnections[$client_id]))
  185. {
  186. $this->_clientConnections[$client_id]->send($data['body']);
  187. }
  188. }
  189. }
  190. else
  191. {
  192. foreach($this->_clientConnections as $client_connection)
  193. {
  194. $client_connection->send($data['body']);
  195. }
  196. }
  197. break;
  198. case GatewayProtocol::CMD_UPDATE_SESSION:
  199. if(isset($this->_clientConnections[$data['client_id']]))
  200. {
  201. $this->_clientConnections[$data['client_id']]->session = $data['ext_data'];
  202. }
  203. break;
  204. case GatewayProtocol::CMD_GET_ONLINE_STATUS:
  205. $online_status = json_encode(array_keys($this->_clientConnections));
  206. $connection->send($online_status);
  207. break;
  208. case GatewayProtocol::CMD_IS_ONLINE:
  209. $connection->send((int)isset($this->_clientConnections[$data['client_id']]));
  210. break;
  211. default :
  212. $err_msg = "gateway inner pack err cmd=$cmd";
  213. throw new \Exception($err_msg);
  214. }
  215. }
  216. public function onWorkerClose($connection)
  217. {
  218. $this->log("{$connection->remoteAddress} CLOSE INNER_CONNECTION\n");
  219. unset($this->_workerConnections[$connection->remoteAddress]);
  220. }
  221. /**
  222. * 存储全局的通信地址
  223. * @param string $address
  224. */
  225. protected function registerAddress()
  226. {
  227. $address = $this->lanIp.':'.$this->lanPort;
  228. // key
  229. $key = 'GLOBAL_GATEWAY_ADDRESS';
  230. try
  231. {
  232. $store = Store::instance('gateway');
  233. }
  234. catch(\Exception $msg)
  235. {
  236. $this->log($msg);
  237. return false;
  238. }
  239. Lock::get();
  240. $addresses_list = $store->get($key);
  241. if(empty($addresses_list))
  242. {
  243. $addresses_list = array();
  244. }
  245. $addresses_list[$address] = $address;
  246. if(!$store->set($key, $addresses_list))
  247. {
  248. Lock::release();
  249. if(get_class($store) == 'Memcached')
  250. {
  251. $msg = " registerAddress fail : " . $store->getResultMessage();
  252. }
  253. $this->log($msg);
  254. return false;
  255. }
  256. Lock::release();
  257. return true;
  258. }
  259. /**
  260. * 删除全局的通信地址
  261. * @param string $address
  262. */
  263. protected function unregisterAddress()
  264. {
  265. $address = $this->lanIp.':'.$this->lanPort;
  266. $key = 'GLOBAL_GATEWAY_ADDRESS';
  267. try
  268. {
  269. $store = Store::instance('gateway');
  270. }
  271. catch (\Exception $msg)
  272. {
  273. $this->log($msg);
  274. return false;
  275. }
  276. Lock::get();
  277. $addresses_list = $store->get($key);
  278. if(empty($addresses_list))
  279. {
  280. $addresses_list = array();
  281. }
  282. unset($addresses_list[$address]);
  283. if(!$store->set($key, $addresses_list))
  284. {
  285. Lock::release();
  286. $msg = "unregisterAddress fail";
  287. if(get_class($store) == 'Memcached')
  288. {
  289. $msg .= " reason:".$store->getResultMessage();
  290. }
  291. $this->log($msg);
  292. return;
  293. }
  294. Lock::release();
  295. return true;
  296. }
  297. public function ping()
  298. {
  299. // 关闭未回复心跳的连接
  300. foreach($this->_clientConnections as $connection)
  301. {
  302. // 上次发送的心跳还没有回复次数大于限定值就断开
  303. if($this->pingNotResponseLimit > 0 && $connection->pingNotResponseCount >= $this->pingNotResponseLimit)
  304. {
  305. $connection->close();
  306. continue;
  307. }
  308. $connection->pingNotResponseCount++;
  309. $connection->send($this->pingData);
  310. }
  311. }
  312. public function onWorkerStop()
  313. {
  314. $this->unregisterAddress();
  315. foreach($this->_clientConnections as $connection)
  316. {
  317. $this->delClientAddress($connection->globalClientId);
  318. }
  319. }
  320. }