Gateway.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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 = 1;
  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. $ping_not_response_limit = (int)\Man\Core\Lib\Config::get($this->workerName.'.ping_not_response_limit');
  191. if($ping_not_response_limit > 0)
  192. {
  193. $this->pingNotResponseLimit = $ping_not_response_limit;
  194. }
  195. // 设置定时任务,发送心跳
  196. if($this->pingInterval > 0 && $this->pingData)
  197. {
  198. \Man\Core\Lib\Task::init($this->event);
  199. \Man\Core\Lib\Task::add($this->pingInterval, array($this, 'ping'));
  200. }
  201. // 主体循环,整个子进程会阻塞在这个函数上
  202. $ret = $this->event->loop();
  203. // 下面正常不会执行到
  204. $this->notice('worker loop exit');
  205. // 执行到就退出
  206. exit(0);
  207. }
  208. /**
  209. * 接受一个链接
  210. * @param resource $socket
  211. * @param $null_one $flag
  212. * @param $null_two $base
  213. * @return void
  214. */
  215. public function accept($socket, $null_one = null, $null_two = null)
  216. {
  217. // 获得一个连接
  218. $new_connection = @stream_socket_accept($socket, 0);
  219. // 可能是惊群效应
  220. if(false === $new_connection)
  221. {
  222. $this->statusInfo['thunder_herd']++;
  223. return false;
  224. }
  225. // 连接的fd序号
  226. $fd = (int) $new_connection;
  227. $this->connections[$fd] = $new_connection;
  228. $this->recvBuffers[$fd] = array('buf'=>'', 'remain_len'=>$this->prereadLength);
  229. $this->connSessionMap[$fd] = '';
  230. // 非阻塞
  231. stream_set_blocking($this->connections[$fd], 0);
  232. $this->event->add($this->connections[$fd], Man\Core\Events\BaseEvent::EV_READ , array($this, 'dealInputBase'), $fd);
  233. // 全局唯一client_id
  234. $global_client_id = $this->createGlobalClientId();
  235. $this->clientConnMap[$global_client_id] = $fd;
  236. $this->connClientMap[$fd] = $global_client_id;
  237. $address = array('local_ip'=>$this->lanIp, 'local_port'=>$this->lanPort, 'socket_id'=>$fd);
  238. // 保存客户端内部通讯地址
  239. if(!Store::instance('gateway')->set($global_client_id, $address))
  240. {
  241. $this->notice("Store::instance('gateway')->set($global_client_id, ".json_encode($address).") fail");
  242. }
  243. // 客户端保存 ip:port
  244. $address= $this->getRemoteAddress($fd);
  245. if($address)
  246. {
  247. list($client_ip, $client_port) = explode(':', $address, 2);
  248. }
  249. else
  250. {
  251. $client_ip = 0;
  252. $client_port = 0;
  253. }
  254. $this->connRemoteAddressMap[$fd] = array('ip'=>$client_ip, 'port'=>$client_port);
  255. // 触发GatewayOnConnection事件
  256. if(method_exists('Event','onGatewayConnect'))
  257. {
  258. $this->sendToWorker(GatewayProtocol::CMD_ON_GATEWAY_CONNECTION, $fd);
  259. }
  260. return $new_connection;
  261. }
  262. /**
  263. * 存储全局的通信地址
  264. * @param string $address
  265. */
  266. protected function registerAddress($address)
  267. {
  268. // 这里使用了信号量只能实现单机互斥,分布式互斥需要借助于memcache incr 或者其他分布式存储
  269. \Man\Core\Lib\Mutex::get();
  270. $key = 'GLOBAL_GATEWAY_ADDRESS';
  271. $addresses_list = Store::instance('gateway')->get($key);
  272. if(empty($addresses_list))
  273. {
  274. $addresses_list = array();
  275. }
  276. $addresses_list[$address] = $address;
  277. Store::instance('gateway')->set($key, $addresses_list);
  278. \Man\Core\Lib\Mutex::release();
  279. }
  280. /**
  281. * 删除全局的通信地址
  282. * @param string $address
  283. */
  284. protected function unregisterAddress($address)
  285. {
  286. // 这里使用了信号量只能实现单机互斥,分布式互斥需要借助于memcache incr 或者其他分布式存储
  287. \Man\Core\Lib\Mutex::get();
  288. $key = 'GLOBAL_GATEWAY_ADDRESS';
  289. $addresses_list = Store::instance('gateway')->get($key);
  290. if(empty($addresses_list))
  291. {
  292. $addresses_list = array();
  293. }
  294. unset($addresses_list[$address]);
  295. Store::instance('gateway')->set($key, $addresses_list);
  296. \Man\Core\Lib\Mutex::release();
  297. }
  298. /**
  299. * 接收Udp数据
  300. * 如果数据超过一个udp包长,需要业务自己解析包体,判断数据是否全部到达
  301. * @param resource $socket
  302. * @param $null_one $flag
  303. * @param $null_two $base
  304. * @return void
  305. */
  306. public function recvInnerUdp($socket, $null_one = null, $null_two = null)
  307. {
  308. $data = stream_socket_recvfrom($socket , self::MAX_UDP_PACKEG_SIZE, 0, $address);
  309. // 惊群效应
  310. if(false === $data || empty($address))
  311. {
  312. return false;
  313. }
  314. $this->currentClientAddress = $address;
  315. $this->innerDealProcess($data);
  316. }
  317. /**
  318. * 内部通讯端口接受BusinessWorker连接请求,以便建立起长连接
  319. * @param resouce $socket
  320. * @param null $null_one
  321. * @param null $null_two
  322. */
  323. public function acceptInnerTcp($socket, $null_one = null, $null_two = null)
  324. {
  325. // 获得一个连接
  326. $new_connection = @stream_socket_accept($socket, 0);
  327. if(false === $new_connection)
  328. {
  329. return false;
  330. }
  331. // 连接的fd序号
  332. $fd = (int) $new_connection;
  333. $this->connections[$fd] = $new_connection;
  334. $this->recvBuffers[$fd] = array('buf'=>'', 'remain_len'=>GatewayProtocol::HEAD_LEN);
  335. // 非阻塞
  336. stream_set_blocking($this->connections[$fd], 0);
  337. $this->event->add($this->connections[$fd], \Man\Core\Events\BaseEvent::EV_READ , array($this, 'recvInnerTcp'), $fd);
  338. // 标记这个连接是内部通讯长连接,区别于客户端连接
  339. $this->workerConnections[$fd] = $fd;
  340. return $new_connection;
  341. }
  342. /**
  343. * 内部通讯判断数据是否全部到达
  344. * @param string $buffer
  345. */
  346. public function dealInnerInput($buffer)
  347. {
  348. return GatewayProtocol::input($buffer);
  349. }
  350. /**
  351. * 处理内部通讯收到的数据
  352. * @param event_buffer $event_buffer
  353. * @param int $fd
  354. * @return void
  355. */
  356. public function recvInnerTcp($connection, $flag, $fd = null)
  357. {
  358. $this->currentDealFd = $fd;
  359. $buffer = stream_socket_recvfrom($connection, $this->recvBuffers[$fd]['remain_len']);
  360. // 出错了
  361. if('' == $buffer && '' == ($buffer = fread($connection, $this->recvBuffers[$fd]['remain_len'])))
  362. {
  363. // 判断是否是链接断开
  364. if(!feof($connection))
  365. {
  366. return;
  367. }
  368. // 如果该链接对应的buffer有数据,说明发生错误
  369. if(!empty($this->recvBuffers[$fd]['buf']))
  370. {
  371. $this->statusInfo['send_fail']++;
  372. $this->notice("INNER_CLIENT_CLOSE\nCLIENT_IP:".$this->getRemoteIp()."\nBUFFER:[".bin2hex($this->recvBuffers[$fd]['buf'])."]\n");
  373. }
  374. // 关闭链接
  375. $this->closeInnerClient($fd);
  376. if($this->workerStatus == self::STATUS_SHUTDOWN)
  377. {
  378. $this->stop();
  379. }
  380. return;
  381. }
  382. $this->recvBuffers[$fd]['buf'] .= $buffer;
  383. $remain_len = $this->dealInnerInput($this->recvBuffers[$fd]['buf']);
  384. // 包接收完毕
  385. if(0 === $remain_len)
  386. {
  387. // 执行处理
  388. try{
  389. // 内部通讯业务处理
  390. $this->innerDealProcess($this->recvBuffers[$fd]['buf']);
  391. }
  392. catch(\Exception $e)
  393. {
  394. $this->notice('CODE:' . $e->getCode() . ' MESSAGE:' . $e->getMessage()."\n".$e->getTraceAsString()."\nCLIENT_IP:".$this->getRemoteIp()."\nBUFFER:[".var_export($this->recvBuffers[$fd]['buf'],true)."]\n");
  395. $this->statusInfo['throw_exception'] ++;
  396. }
  397. $this->recvBuffers[$fd] = array('buf'=>'', 'remain_len'=>GatewayProtocol::HEAD_LEN);
  398. }
  399. // 出错
  400. else if(false === $remain_len)
  401. {
  402. // 出错
  403. $this->statusInfo['packet_err']++;
  404. $this->notice("INNER_PACKET_ERROR\nCLIENT_IP:".$this->getRemoteIp()."\nBUFFER:[".var_export($this->recvBuffers[$fd]['buf'],true)."]\n");
  405. $this->closeInnerClient($fd);
  406. }
  407. else
  408. {
  409. $this->recvBuffers[$fd]['remain_len'] = $remain_len;
  410. }
  411. // 检查是否是关闭状态或者是否到达请求上限
  412. if($this->workerStatus == self::STATUS_SHUTDOWN )
  413. {
  414. // 停止服务
  415. $this->stop();
  416. // EXIT_WAIT_TIME秒后退出进程
  417. pcntl_alarm(self::EXIT_WAIT_TIME);
  418. }
  419. }
  420. /**
  421. * 内部通讯处理
  422. * @param string $recv_buffer
  423. */
  424. public function innerDealProcess($recv_buffer)
  425. {
  426. $pack = new GatewayProtocol($recv_buffer);
  427. $cmd = $pack->header['cmd'];
  428. StatisticClient::tick();
  429. $module = __CLASS__;
  430. $interface = isset(self::$interfaceMap[$cmd]) ? self::$interfaceMap[$cmd] : $cmd;
  431. $success = 1;
  432. $code = 0;
  433. $msg = '';
  434. try
  435. {
  436. switch($cmd)
  437. {
  438. // 向某客户端发送数据
  439. case GatewayProtocol::CMD_SEND_TO_ONE:
  440. $this->sendToSocketId($pack->header['socket_id'], $pack->body);
  441. break;
  442. // 踢掉客户端
  443. case GatewayProtocol::CMD_KICK:
  444. $this->closeClient($pack->header['socket_id']);
  445. break;
  446. // 向所客户端发送数据
  447. case GatewayProtocol::CMD_SEND_TO_ALL:
  448. if($pack->ext_data)
  449. {
  450. $client_id_array = unpack('N*', $pack->ext_data);
  451. foreach($client_id_array as $client_id)
  452. {
  453. if(isset($this->clientConnMap[$client_id]))
  454. {
  455. $this->sendToSocketId($this->clientConnMap[$client_id], $pack->body);
  456. }
  457. }
  458. }
  459. else
  460. {
  461. $this->broadCast($pack->body);
  462. }
  463. break;
  464. // 更新某个客户端的session
  465. case GatewayProtocol::CMD_UPDATE_SESSION:
  466. if(isset($this->connSessionMap[$pack->header['socket_id']]))
  467. {
  468. $this->connSessionMap[$pack->header['socket_id']] = $pack->ext_data;
  469. }
  470. break;
  471. // 获得在线状态
  472. case GatewayProtocol::CMD_GET_ONLINE_STATUS:
  473. $online_status = json_encode(array_values($this->connClientMap));
  474. stream_socket_sendto($this->innerMainSocketUdp, $online_status, 0, $this->currentClientAddress);
  475. break;
  476. // 判断某个客户端id是否在线
  477. case GatewayProtocol::CMD_IS_ONLINE:
  478. stream_socket_sendto($this->innerMainSocketUdp, (int)isset($this->clientConnMap[$pack->header['client_id']]), 0, $this->currentClientAddress);
  479. break;
  480. // 未知的命令
  481. default :
  482. $err_msg = "gateway inner pack err cmd=$cmd";
  483. $this->notice($err_msg);
  484. throw new \Exception($err_msg, 501);
  485. }
  486. }
  487. catch(\Exception $e)
  488. {
  489. $success = 0;
  490. $code = $e->getCode() > 0 ? $e->getCode() : 500;
  491. $msg = $e->__toString();
  492. }
  493. StatisticClient::report($module, $interface, $success, $code, $msg);
  494. }
  495. /**
  496. * 广播数据
  497. * @param string $bin_data
  498. */
  499. protected function broadCast($bin_data)
  500. {
  501. foreach($this->clientConnMap as $client_id=>$conn)
  502. {
  503. $this->sendToSocketId($conn, $bin_data);
  504. }
  505. }
  506. /**
  507. * 根据client_id获取client_id对应连接的socket_id
  508. * @param int $client_id
  509. */
  510. protected function getFdByClientId($client_id)
  511. {
  512. if(isset($this->clientConnMap[$client_id]))
  513. {
  514. return $this->clientConnMap[$client_id];
  515. }
  516. return 0;
  517. }
  518. /**
  519. * 根据连接socket_id获取client_id
  520. * @param int $fd
  521. */
  522. protected function getClientIdByFd($fd)
  523. {
  524. if(isset($this->connClientMap[$fd]))
  525. {
  526. return $this->connClientMap[$fd];
  527. }
  528. return 0;
  529. }
  530. /**
  531. * 向某个socket_id的连接发送消息
  532. * @param int $socket_id
  533. * @param string $bin_data
  534. */
  535. public function sendToSocketId($socket_id, $bin_data)
  536. {
  537. if(!isset($this->connections[$socket_id]))
  538. {
  539. return false;
  540. }
  541. $this->currentDealFd = $socket_id;
  542. return $this->sendToClient($bin_data);
  543. }
  544. /**
  545. * 用户客户端关闭连接时触发
  546. * @see Man\Core.SocketWorker::closeClient()
  547. */
  548. protected function closeClient($fd)
  549. {
  550. StatisticClient::tick();
  551. if($client_id = $this->getClientIdByFd($fd))
  552. {
  553. $this->sendToWorker(GatewayProtocol::CMD_ON_CLOSE, $fd);
  554. Store::instance('gateway')->delete($client_id);
  555. unset($this->clientConnMap[$client_id]);
  556. }
  557. unset($this->connClientMap[$fd], $this->connSessionMap[$fd], $this->connRemoteAddressMap[$fd]);
  558. parent::closeClient($fd);
  559. StatisticClient::report(__CLASS__, 'CMD_ON_CLOSE', 1, 0, '');
  560. }
  561. /**
  562. * 内部通讯socket在BusinessWorker主动关闭连接时触发
  563. * @param int $fd
  564. */
  565. protected function closeInnerClient($fd)
  566. {
  567. unset($this->workerConnections[$fd]);
  568. parent::closeClient($fd);
  569. }
  570. /**
  571. * 随机抽取一个与BusinessWorker的长连接,将数据发给一个BusinessWorker
  572. * @param int $cmd
  573. * @param int $socket_id
  574. * @param string $body
  575. */
  576. protected function sendToWorker($cmd, $socket_id, $body = '')
  577. {
  578. $pack = new GatewayProtocol();
  579. $pack->header['cmd'] = $cmd;
  580. $pack->header['local_ip'] = $this->lanIp;
  581. $pack->header['local_port'] = $this->lanPort;
  582. $pack->header['socket_id'] = $socket_id;
  583. $pack->header['client_ip'] = $this->connRemoteAddressMap[$socket_id]['ip'];
  584. $pack->header['client_port'] = $this->connRemoteAddressMap[$socket_id]['port'];
  585. $pack->header['client_id'] = $this->getClientIdByFd($socket_id);
  586. $pack->body = $body;
  587. $pack->ext_data = $this->connSessionMap[$pack->header['socket_id']];
  588. return $this->sendBufferToWorker($pack->getBuffer());
  589. }
  590. /**
  591. * 随机抽取一个与BusinessWorker的长连接,将数据发给一个BusinessWorker
  592. * @param string $bin_data
  593. */
  594. protected function sendBufferToWorker($bin_data)
  595. {
  596. if($this->currentDealFd = array_rand($this->workerConnections))
  597. {
  598. return $this->sendToClient($bin_data);
  599. }
  600. else
  601. {
  602. $this->notice("sendBufferToWorker fail \$this->workerConnections=".var_export($this->workerConnections,true));
  603. }
  604. }
  605. /**
  606. * 打印日志
  607. * @see Man\Core.AbstractWorker::notice()
  608. */
  609. protected function notice($str, $display=true)
  610. {
  611. $str = 'Worker['.get_class($this).']:'."$str ip:".$this->getRemoteIp();
  612. Man\Core\Lib\Log::add($str);
  613. if($display && Man\Core\Lib\Config::get('workerman.debug') == 1)
  614. {
  615. echo $str."\n";
  616. }
  617. }
  618. /**
  619. * 进程停止时,清除一些数据
  620. * @see Man\Core.SocketWorker::onStop()
  621. */
  622. public function onStop()
  623. {
  624. $this->unregisterAddress($this->lanIp.':'.$this->lanPort);
  625. foreach($this->connClientMap as $client_id)
  626. {
  627. Store::instance('gateway')->delete($client_id);
  628. }
  629. }
  630. /**
  631. * 创建全局唯一的id
  632. */
  633. protected function createGlobalClientId()
  634. {
  635. $global_socket_key = 'GLOBAL_SOCKET_ID_KEY';
  636. $global_client_id = Store::instance('gateway')->increment($global_socket_key);
  637. if(!$global_client_id || $global_client_id > 2147483646)
  638. {
  639. Store::instance('gateway')->set($global_socket_key, 1);
  640. }
  641. else
  642. {
  643. return $global_client_id;
  644. }
  645. return Store::instance('gateway')->increment($global_socket_key);
  646. }
  647. /**
  648. * 向客户端发送心跳数据
  649. * 并把没回应心跳的客户端踢掉
  650. */
  651. public function ping()
  652. {
  653. // 清理下线的链接
  654. foreach($this->pingInfo as $client_id=>$not_response_count)
  655. {
  656. // 已经下线的忽略
  657. if(!isset($this->clientConnMap[$client_id]))
  658. {
  659. unset($this->pingInfo[$client_id]);
  660. continue;
  661. }
  662. // 上次发送的心跳还没有回复次数大于限定值就断开
  663. if($not_response_count >= $this->pingNotResponseLimit)
  664. {
  665. $this->closeClient($this->clientConnMap[$client_id]);
  666. }
  667. }
  668. // 向所有链接发送心跳数据
  669. foreach($this->clientConnMap as $client_id=>$conn)
  670. {
  671. $this->sendToSocketId($conn, $this->pingData);
  672. if(isset($this->pingInfo[$client_id]))
  673. {
  674. $this->pingInfo[$client_id]++;
  675. }
  676. else
  677. {
  678. $this->pingInfo[$client_id] = 1;
  679. }
  680. }
  681. }
  682. }