Gateway.php 23 KB

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