Gateway.php 11 KB

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