Gateway.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. <?php
  2. /**
  3. *
  4. * 暴露给客户端的连接网关 只负责网络io
  5. * 1、监听客户端连接
  6. * 2、监听后端回应并转发回应给前端
  7. *
  8. * @author walkor <workerman.net>
  9. *
  10. */
  11. require_once __DIR__ . '/../Lib/Autoloader.php';
  12. use \Protocols\GatewayProtocol;
  13. use \Lib\Store;
  14. use \Lib\StatisticClient;
  15. class Gateway extends Man\Core\SocketWorker
  16. {
  17. /**
  18. * 内部通信socket udp
  19. * @var resouce
  20. */
  21. protected $innerMainSocketUdp = null;
  22. /**
  23. * 内部通信socket tcp
  24. * @var resouce
  25. */
  26. protected $innerMainSocketTcp = null;
  27. /**
  28. * 内网ip
  29. * @var string
  30. */
  31. protected $lanIp = '127.0.0.1';
  32. /**
  33. * 内部通信端口
  34. * @var int
  35. */
  36. protected $lanPort = 0;
  37. /**
  38. * client_id到连接的映射
  39. * @var array
  40. */
  41. protected $clientConnMap = array();
  42. /**
  43. * 连接到client_id的映射
  44. * @var array
  45. */
  46. protected $connClientMap = array();
  47. /**
  48. * 客户端链接和客户端远程地址映射
  49. * @var array
  50. */
  51. protected $connRemoteAddressMap = array();
  52. /**
  53. * client_id到session的映射
  54. * @var array
  55. */
  56. protected $connSessionMap = array();
  57. /**
  58. * 与worker的连接
  59. * [fd=>fd, $fd=>fd, ..]
  60. * @var array
  61. */
  62. protected $workerConnections = array();
  63. /**
  64. * 客户端心跳信息
  65. * [client_id=>not_response_count, client_id=>not_response_count, ..]
  66. */
  67. protected $pingInfo = array();
  68. /**
  69. * gateway 发送心跳时间间隔 单位:秒 ,0表示不发送心跳,在配置中设置
  70. * @var integer
  71. */
  72. protected $pingInterval = 0;
  73. /**
  74. * 心跳数据
  75. * 可以是二进制数据(二进制数据保存在文件中,在配置中设置ping数据文件路径 如 ping_data=/yourpath/ping.bin)
  76. * ping数据应该是客户端能够识别的数据格式,客户端必须回复心跳,不然链接会断开
  77. * @var string
  78. */
  79. protected $pingData = '';
  80. /**
  81. * 客户端连续$pingNotResponseLimit次不回应心跳则断开链接
  82. */
  83. protected $pingNotResponseLimit = 0;
  84. /**
  85. * 命令字,统计用到
  86. * @var array
  87. */
  88. protected static $interfaceMap = array(
  89. GatewayProtocol::CMD_SEND_TO_ONE => 'CMD_SEND_TO_ONE',
  90. GatewayProtocol::CMD_SEND_TO_ALL => 'CMD_SEND_TO_ALL',
  91. GatewayProtocol::CMD_KICK => 'CMD_KICK',
  92. GatewayProtocol::CMD_UPDATE_SESSION => 'CMD_UPDATE_SESSION',
  93. GatewayProtocol::CMD_GET_ONLINE_STATUS => 'CMD_GET_ONLINE_STATUS',
  94. GatewayProtocol::CMD_IS_ONLINE => 'CMD_IS_ONLINE',
  95. );
  96. /**
  97. * 由于网络延迟或者socket缓冲区大小的限制,客户端发来的数据可能不会都全部到达,需要根据协议判断数据是否完整
  98. * @see Man\Core.SocketWorker::dealInput()
  99. */
  100. public function dealInput($recv_buffer)
  101. {
  102. // 只要客户端有回应就是没掉线
  103. if(!empty($this->pingInfo[$this->connClientMap[$this->currentDealFd]]))
  104. {
  105. $this->pingInfo[$this->connClientMap[$this->currentDealFd]] = 0;
  106. }
  107. // 处理粘包
  108. return call_user_func_array(array('Event', 'onGatewayMessage'), array($recv_buffer));
  109. }
  110. /**
  111. * 用户客户端发来消息时处理
  112. * @see Man\Core.SocketWorker::dealProcess()
  113. */
  114. public function dealProcess($recv_buffer)
  115. {
  116. // 统计打点
  117. StatisticClient::tick();
  118. $module = __CLASS__;
  119. $success = 1;
  120. $code = 0;
  121. $msg = '';
  122. $interface = 'CMD_ON_MESSAGE';
  123. // 触发ON_MESSAGE
  124. $ret =$this->sendToWorker(GatewayProtocol::CMD_ON_MESSAGE, $this->currentDealFd, $recv_buffer);
  125. if($ret === false)
  126. {
  127. $success = 0;
  128. $msg = 'sendToWorker(CMD_ON_MESSAGE, '.$this->currentDealFd.', strlen($recv_buffer) = '.strlen($recv_buffer).') fail ';
  129. $code = 102;
  130. }
  131. StatisticClient::report($module, $interface, $success, $code, $msg);
  132. }
  133. /**
  134. * 进程启动
  135. */
  136. public function start()
  137. {
  138. // 安装信号处理函数
  139. $this->installSignal();
  140. // 添加accept事件
  141. $ret = $this->event->add($this->mainSocket, Man\Core\Events\BaseEvent::EV_READ, array($this, 'accept'));
  142. // 创建内部通信套接字,用于与BusinessWorker通讯
  143. $start_port = Man\Core\Lib\Config::get($this->workerName.'.lan_port_start');
  144. // 计算本进程监听的ip端口
  145. $this->lanPort = $start_port - posix_getppid() + posix_getpid();
  146. $this->lanIp = Man\Core\Lib\Config::get($this->workerName.'.lan_ip');
  147. if(!$this->lanIp)
  148. {
  149. $this->notice($this->workerName.'.lan_ip not set');
  150. $this->lanIp = '127.0.0.1';
  151. }
  152. $error_no_udp = $error_no_tcp = 0;
  153. $error_msg_udp = $error_msg_tcp = '';
  154. // 执行监听
  155. $this->innerMainSocketUdp = stream_socket_server("udp://".$this->lanIp.':'.$this->lanPort, $error_no_udp, $error_msg_udp, STREAM_SERVER_BIND);
  156. $this->innerMainSocketTcp = stream_socket_server("tcp://".$this->lanIp.':'.$this->lanPort, $error_no_tcp, $error_msg_tcp, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN);
  157. // 出错,退出,下次会换个端口
  158. if(!$this->innerMainSocketUdp || !$this->innerMainSocketTcp)
  159. {
  160. $this->notice('create innerMainSocket udp or tcp fail and exit '.$error_msg_udp.$error_msg_tcp);
  161. $this->stop();
  162. }
  163. else
  164. {
  165. stream_set_blocking($this->innerMainSocketUdp , 0);
  166. stream_set_blocking($this->innerMainSocketTcp , 0);
  167. }
  168. // 注册套接字
  169. $this->registerAddress($this->lanIp.':'.$this->lanPort);
  170. // 添加读udp/tcp事件
  171. $this->event->add($this->innerMainSocketUdp, Man\Core\Events\BaseEvent::EV_READ, array($this, 'recvInnerUdp'));
  172. $this->event->add($this->innerMainSocketTcp, Man\Core\Events\BaseEvent::EV_READ, array($this, 'acceptInnerTcp'));
  173. // 初始化心跳包时间间隔
  174. $ping_interval = \Man\Core\Lib\Config::get($this->workerName.'.ping_interval');
  175. if((int)$ping_interval > 0)
  176. {
  177. $this->pingInterval = (int)$ping_interval;
  178. }
  179. // 获取心跳包数据
  180. $ping_data_or_path = \Man\Core\Lib\Config::get($this->workerName.'.ping_data');
  181. if(is_file($ping_data_or_path))
  182. {
  183. $this->pingData = file_get_contents($ping_data_or_path);
  184. }
  185. else
  186. {
  187. $this->pingData = $ping_data_or_path;
  188. }
  189. // 不返回心跳回应的限定值
  190. $this->pingNotResponseLimit = (int)\Man\Core\Lib\Config::get($this->workerName.'.ping_not_response_limit');
  191. // 设置定时任务,发送心跳
  192. if($this->pingInterval > 0 && $this->pingData)
  193. {
  194. \Man\Core\Lib\Task::init($this->event);
  195. \Man\Core\Lib\Task::add($this->pingInterval, array($this, 'ping'));
  196. }
  197. // 主体循环,整个子进程会阻塞在这个函数上
  198. $ret = $this->event->loop();
  199. // 下面正常不会执行到
  200. $this->notice('worker loop exit');
  201. // 执行到就退出
  202. exit(0);
  203. }
  204. /**
  205. * 接受一个链接
  206. * @param resource $socket
  207. * @param $null_one $flag
  208. * @param $null_two $base
  209. * @return void
  210. */
  211. public function accept($socket, $null_one = null, $null_two = null)
  212. {
  213. // 获得一个连接
  214. $new_connection = @stream_socket_accept($socket, 0);
  215. // 可能是惊群效应
  216. if(false === $new_connection)
  217. {
  218. $this->statusInfo['thunder_herd']++;
  219. return false;
  220. }
  221. // 连接的fd序号
  222. $fd = (int) $new_connection;
  223. $this->connections[$fd] = $new_connection;
  224. $this->recvBuffers[$fd] = array('buf'=>'', 'remain_len'=>$this->prereadLength);
  225. $this->connSessionMap[$fd] = '';
  226. // 非阻塞
  227. stream_set_blocking($this->connections[$fd], 0);
  228. $this->event->add($this->connections[$fd], Man\Core\Events\BaseEvent::EV_READ , array($this, 'dealInputBase'), $fd);
  229. // 全局唯一client_id
  230. $global_client_id = $this->createGlobalClientId();
  231. $this->clientConnMap[$global_client_id] = $fd;
  232. $this->connClientMap[$fd] = $global_client_id;
  233. $address = array('local_ip'=>$this->lanIp, 'local_port'=>$this->lanPort, 'socket_id'=>$fd);
  234. // 保存客户端内部通讯地址
  235. if(!Store::instance('gateway')->set($global_client_id, $address))
  236. {
  237. $this->notice("Store::instance('gateway')->set($global_client_id, ".json_encode($address).") fail");
  238. }
  239. // 客户端保存 ip:port
  240. $address= $this->getRemoteAddress($fd);
  241. if($address)
  242. {
  243. list($client_ip, $client_port) = explode(':', $address, 2);
  244. }
  245. else
  246. {
  247. $client_ip = 0;
  248. $client_port = 0;
  249. }
  250. $this->connRemoteAddressMap[$fd] = array('ip'=>$client_ip, 'port'=>$client_port);
  251. // 触发GatewayOnConnection事件
  252. if(method_exists('Event','onGatewayConnect'))
  253. {
  254. $this->sendToWorker(GatewayProtocol::CMD_ON_GATEWAY_CONNECTION, $fd);
  255. }
  256. return $new_connection;
  257. }
  258. /**
  259. * 存储全局的通信地址
  260. * @param string $address
  261. */
  262. protected function registerAddress($address)
  263. {
  264. // 这里使用了信号量只能实现单机互斥,分布式互斥需要借助于memcache incr 或者其他分布式存储
  265. \Man\Core\Lib\Mutex::get();
  266. $key = 'GLOBAL_GATEWAY_ADDRESS';
  267. $addresses_list = Store::instance('gateway')->get($key);
  268. if(empty($addresses_list))
  269. {
  270. $addresses_list = array();
  271. }
  272. $addresses_list[$address] = $address;
  273. Store::instance('gateway')->set($key, $addresses_list);
  274. \Man\Core\Lib\Mutex::release();
  275. }
  276. /**
  277. * 删除全局的通信地址
  278. * @param string $address
  279. */
  280. protected function unregisterAddress($address)
  281. {
  282. // 这里使用了信号量只能实现单机互斥,分布式互斥需要借助于memcache incr 或者其他分布式存储
  283. \Man\Core\Lib\Mutex::get();
  284. $key = 'GLOBAL_GATEWAY_ADDRESS';
  285. $addresses_list = Store::instance('gateway')->get($key);
  286. if(empty($addresses_list))
  287. {
  288. $addresses_list = array();
  289. }
  290. unset($addresses_list[$address]);
  291. Store::instance('gateway')->set($key, $addresses_list);
  292. \Man\Core\Lib\Mutex::release();
  293. }
  294. /**
  295. * 接收Udp数据
  296. * 如果数据超过一个udp包长,需要业务自己解析包体,判断数据是否全部到达
  297. * @param resource $socket
  298. * @param $null_one $flag
  299. * @param $null_two $base
  300. * @return void
  301. */
  302. public function recvInnerUdp($socket, $null_one = null, $null_two = null)
  303. {
  304. $data = stream_socket_recvfrom($socket , self::MAX_UDP_PACKEG_SIZE, 0, $address);
  305. // 惊群效应
  306. if(false === $data || empty($address))
  307. {
  308. return false;
  309. }
  310. $this->currentClientAddress = $address;
  311. $this->innerDealProcess($data);
  312. }
  313. /**
  314. * 内部通讯端口接受BusinessWorker连接请求,以便建立起长连接
  315. * @param resouce $socket
  316. * @param null $null_one
  317. * @param null $null_two
  318. */
  319. public function acceptInnerTcp($socket, $null_one = null, $null_two = null)
  320. {
  321. // 获得一个连接
  322. $new_connection = @stream_socket_accept($socket, 0);
  323. if(false === $new_connection)
  324. {
  325. return false;
  326. }
  327. // 连接的fd序号
  328. $fd = (int) $new_connection;
  329. $this->connections[$fd] = $new_connection;
  330. $this->recvBuffers[$fd] = array('buf'=>'', 'remain_len'=>GatewayProtocol::HEAD_LEN);
  331. // 非阻塞
  332. stream_set_blocking($this->connections[$fd], 0);
  333. $this->event->add($this->connections[$fd], \Man\Core\Events\BaseEvent::EV_READ , array($this, 'recvInnerTcp'), $fd);
  334. // 标记这个连接是内部通讯长连接,区别于客户端连接
  335. $this->workerConnections[$fd] = $fd;
  336. return $new_connection;
  337. }
  338. /**
  339. * 内部通讯判断数据是否全部到达
  340. * @param string $buffer
  341. */
  342. public function dealInnerInput($buffer)
  343. {
  344. return GatewayProtocol::input($buffer);
  345. }
  346. /**
  347. * 处理内部通讯收到的数据
  348. * @param event_buffer $event_buffer
  349. * @param int $fd
  350. * @return void
  351. */
  352. public function recvInnerTcp($connection, $flag, $fd = null)
  353. {
  354. $this->currentDealFd = $fd;
  355. $buffer = stream_socket_recvfrom($connection, $this->recvBuffers[$fd]['remain_len']);
  356. // 出错了
  357. if('' == $buffer && '' == ($buffer = fread($connection, $this->recvBuffers[$fd]['remain_len'])))
  358. {
  359. // 判断是否是链接断开
  360. if(!feof($connection))
  361. {
  362. return;
  363. }
  364. // 如果该链接对应的buffer有数据,说明发生错误
  365. if(!empty($this->recvBuffers[$fd]['buf']))
  366. {
  367. $this->statusInfo['send_fail']++;
  368. $this->notice("INNER_CLIENT_CLOSE\nCLIENT_IP:".$this->getRemoteIp()."\nBUFFER:[".bin2hex($this->recvBuffers[$fd]['buf'])."]\n");
  369. }
  370. // 关闭链接
  371. $this->closeInnerClient($fd);
  372. if($this->workerStatus == self::STATUS_SHUTDOWN)
  373. {
  374. $this->stop();
  375. }
  376. return;
  377. }
  378. $this->recvBuffers[$fd]['buf'] .= $buffer;
  379. $remain_len = $this->dealInnerInput($this->recvBuffers[$fd]['buf']);
  380. // 包接收完毕
  381. if(0 === $remain_len)
  382. {
  383. // 执行处理
  384. try{
  385. // 内部通讯业务处理
  386. $this->innerDealProcess($this->recvBuffers[$fd]['buf']);
  387. }
  388. catch(\Exception $e)
  389. {
  390. $this->notice('CODE:' . $e->getCode() . ' MESSAGE:' . $e->getMessage()."\n".$e->getTraceAsString()."\nCLIENT_IP:".$this->getRemoteIp()."\nBUFFER:[".var_export($this->recvBuffers[$fd]['buf'],true)."]\n");
  391. $this->statusInfo['throw_exception'] ++;
  392. }
  393. $this->recvBuffers[$fd] = array('buf'=>'', 'remain_len'=>GatewayProtocol::HEAD_LEN);
  394. }
  395. // 出错
  396. else if(false === $remain_len)
  397. {
  398. // 出错
  399. $this->statusInfo['packet_err']++;
  400. $this->notice("INNER_PACKET_ERROR\nCLIENT_IP:".$this->getRemoteIp()."\nBUFFER:[".var_export($this->recvBuffers[$fd]['buf'],true)."]\n");
  401. $this->closeInnerClient($fd);
  402. }
  403. else
  404. {
  405. $this->recvBuffers[$fd]['remain_len'] = $remain_len;
  406. }
  407. // 检查是否是关闭状态或者是否到达请求上限
  408. if($this->workerStatus == self::STATUS_SHUTDOWN )
  409. {
  410. // 停止服务
  411. $this->stop();
  412. // EXIT_WAIT_TIME秒后退出进程
  413. pcntl_alarm(self::EXIT_WAIT_TIME);
  414. }
  415. }
  416. /**
  417. * 内部通讯处理
  418. * @param string $recv_buffer
  419. */
  420. public function innerDealProcess($recv_buffer)
  421. {
  422. $pack = new GatewayProtocol($recv_buffer);
  423. $cmd = $pack->header['cmd'];
  424. StatisticClient::tick();
  425. $module = __CLASS__;
  426. $interface = isset(self::$interfaceMap[$cmd]) ? self::$interfaceMap[$cmd] : $cmd;
  427. $success = 1;
  428. $code = 0;
  429. $msg = '';
  430. try
  431. {
  432. switch($cmd)
  433. {
  434. // 向某客户端发送数据
  435. case GatewayProtocol::CMD_SEND_TO_ONE:
  436. $this->sendToSocketId($pack->header['socket_id'], $pack->body);
  437. break;
  438. // 踢掉客户端
  439. case GatewayProtocol::CMD_KICK:
  440. $this->closeClient($pack->header['socket_id']);
  441. break;
  442. // 向所客户端发送数据
  443. case GatewayProtocol::CMD_SEND_TO_ALL:
  444. if($pack->ext_data)
  445. {
  446. $client_id_array = unpack('N*', $pack->ext_data);
  447. foreach($client_id_array as $client_id)
  448. {
  449. if(isset($this->clientConnMap[$client_id]))
  450. {
  451. $this->sendToSocketId($this->clientConnMap[$client_id], $pack->body);
  452. }
  453. }
  454. }
  455. else
  456. {
  457. $this->broadCast($pack->body);
  458. }
  459. break;
  460. // 更新某个客户端的session
  461. case GatewayProtocol::CMD_UPDATE_SESSION:
  462. if(isset($this->connSessionMap[$pack->header['socket_id']]))
  463. {
  464. $this->connSessionMap[$pack->header['socket_id']] = $pack->ext_data;
  465. }
  466. break;
  467. // 获得在线状态
  468. case GatewayProtocol::CMD_GET_ONLINE_STATUS:
  469. $online_status = json_encode(array_values($this->connClientMap));
  470. stream_socket_sendto($this->innerMainSocketUdp, $online_status, 0, $this->currentClientAddress);
  471. break;
  472. // 判断某个客户端id是否在线
  473. case GatewayProtocol::CMD_IS_ONLINE:
  474. stream_socket_sendto($this->innerMainSocketUdp, (int)isset($this->clientConnMap[$pack->header['client_id']]), 0, $this->currentClientAddress);
  475. break;
  476. // 未知的命令
  477. default :
  478. $err_msg = "gateway inner pack err cmd=$cmd";
  479. $this->notice($err_msg);
  480. throw new \Exception($err_msg, 501);
  481. }
  482. }
  483. catch(\Exception $e)
  484. {
  485. $success = 0;
  486. $code = $e->getCode() > 0 ? $e->getCode() : 500;
  487. $msg = $e->__toString();
  488. }
  489. StatisticClient::report($module, $interface, $success, $code, $msg);
  490. }
  491. /**
  492. * 广播数据
  493. * @param string $bin_data
  494. */
  495. protected function broadCast($bin_data)
  496. {
  497. foreach($this->clientConnMap as $client_id=>$conn)
  498. {
  499. $this->sendToSocketId($conn, $bin_data);
  500. }
  501. }
  502. /**
  503. * 根据client_id获取client_id对应连接的socket_id
  504. * @param int $client_id
  505. */
  506. protected function getFdByClientId($client_id)
  507. {
  508. if(isset($this->clientConnMap[$client_id]))
  509. {
  510. return $this->clientConnMap[$client_id];
  511. }
  512. return 0;
  513. }
  514. /**
  515. * 根据连接socket_id获取client_id
  516. * @param int $fd
  517. */
  518. protected function getClientIdByFd($fd)
  519. {
  520. if(isset($this->connClientMap[$fd]))
  521. {
  522. return $this->connClientMap[$fd];
  523. }
  524. return 0;
  525. }
  526. /**
  527. * 向某个socket_id的连接发送消息
  528. * @param int $socket_id
  529. * @param string $bin_data
  530. */
  531. public function sendToSocketId($socket_id, $bin_data)
  532. {
  533. if(!isset($this->connections[$socket_id]))
  534. {
  535. return false;
  536. }
  537. $this->currentDealFd = $socket_id;
  538. return $this->sendToClient($bin_data);
  539. }
  540. /**
  541. * 用户客户端关闭连接时触发
  542. * @see Man\Core.SocketWorker::closeClient()
  543. */
  544. protected function closeClient($fd)
  545. {
  546. StatisticClient::tick();
  547. if($client_id = $this->getClientIdByFd($fd))
  548. {
  549. $this->sendToWorker(GatewayProtocol::CMD_ON_CLOSE, $fd);
  550. Store::instance('gateway')->delete($client_id);
  551. unset($this->clientConnMap[$client_id]);
  552. }
  553. unset($this->connClientMap[$fd], $this->connSessionMap[$fd], $this->connRemoteAddressMap[$fd]);
  554. parent::closeClient($fd);
  555. StatisticClient::report(__CLASS__, 'CMD_ON_CLOSE', 1, 0, '');
  556. }
  557. /**
  558. * 内部通讯socket在BusinessWorker主动关闭连接时触发
  559. * @param int $fd
  560. */
  561. protected function closeInnerClient($fd)
  562. {
  563. unset($this->workerConnections[$fd]);
  564. parent::closeClient($fd);
  565. }
  566. /**
  567. * 随机抽取一个与BusinessWorker的长连接,将数据发给一个BusinessWorker
  568. * @param int $cmd
  569. * @param int $socket_id
  570. * @param string $body
  571. */
  572. protected function sendToWorker($cmd, $socket_id, $body = '')
  573. {
  574. $pack = new GatewayProtocol();
  575. $pack->header['cmd'] = $cmd;
  576. $pack->header['local_ip'] = $this->lanIp;
  577. $pack->header['local_port'] = $this->lanPort;
  578. $pack->header['socket_id'] = $socket_id;
  579. $pack->header['client_ip'] = $this->connRemoteAddressMap[$socket_id]['ip'];
  580. $pack->header['client_port'] = $this->connRemoteAddressMap[$socket_id]['port'];
  581. $pack->header['client_id'] = $this->getClientIdByFd($socket_id);
  582. $pack->body = $body;
  583. $pack->ext_data = $this->connSessionMap[$pack->header['socket_id']];
  584. return $this->sendBufferToWorker($pack->getBuffer());
  585. }
  586. /**
  587. * 随机抽取一个与BusinessWorker的长连接,将数据发给一个BusinessWorker
  588. * @param string $bin_data
  589. */
  590. protected function sendBufferToWorker($bin_data)
  591. {
  592. if($this->currentDealFd = array_rand($this->workerConnections))
  593. {
  594. return $this->sendToClient($bin_data);
  595. }
  596. else
  597. {
  598. $this->notice("sendBufferToWorker fail \$this->workerConnections=".var_export($this->workerConnections,true));
  599. }
  600. }
  601. /**
  602. * 打印日志
  603. * @see Man\Core.AbstractWorker::notice()
  604. */
  605. protected function notice($str, $display=true)
  606. {
  607. $str = 'Worker['.get_class($this).']:'."$str ip:".$this->getRemoteIp();
  608. Man\Core\Lib\Log::add($str);
  609. if($display && Man\Core\Lib\Config::get('workerman.debug') == 1)
  610. {
  611. echo $str."\n";
  612. }
  613. }
  614. /**
  615. * 进程停止时,清除一些数据
  616. * @see Man\Core.SocketWorker::onStop()
  617. */
  618. public function onStop()
  619. {
  620. $this->unregisterAddress($this->lanIp.':'.$this->lanPort);
  621. foreach($this->connClientMap as $client_id)
  622. {
  623. Store::instance('gateway')->delete($client_id);
  624. }
  625. }
  626. /**
  627. * 创建全局唯一的id
  628. */
  629. protected function createGlobalClientId()
  630. {
  631. $global_socket_key = 'GLOBAL_SOCKET_ID_KEY';
  632. $global_client_id = Store::instance('gateway')->increment($global_socket_key);
  633. if(!$global_client_id || $global_client_id > 2147483646)
  634. {
  635. Store::instance('gateway')->set($global_socket_key, 1);
  636. }
  637. else
  638. {
  639. return $global_client_id;
  640. }
  641. return Store::instance('gateway')->increment($global_socket_key);
  642. }
  643. /**
  644. * 向客户端发送心跳数据
  645. * 并把没回应心跳的客户端踢掉
  646. */
  647. public function ping()
  648. {
  649. // 清理下线的链接
  650. foreach($this->pingInfo as $client_id=>$not_response_count)
  651. {
  652. // 已经下线的忽略
  653. if(!isset($this->clientConnMap[$client_id]))
  654. {
  655. unset($this->pingInfo[$client_id]);
  656. continue;
  657. }
  658. // 上次发送的心跳还没有回复次数大于限定值就断开
  659. if($this->pingNotResponseLimit > 0 && $not_response_count >= $this->pingNotResponseLimit)
  660. {
  661. $this->closeClient($this->clientConnMap[$client_id]);
  662. }
  663. }
  664. // 向所有链接发送心跳数据
  665. foreach($this->clientConnMap as $client_id=>$conn)
  666. {
  667. $this->sendToSocketId($conn, $this->pingData);
  668. if(isset($this->pingInfo[$client_id]))
  669. {
  670. $this->pingInfo[$client_id]++;
  671. }
  672. else
  673. {
  674. $this->pingInfo[$client_id] = 1;
  675. }
  676. }
  677. }
  678. }