Channel组件源码分析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/themagickeyjianan/article/details/88784543

背景:

channel的概念十分重要,因为这是分布式系统的核心,将位于不同服务器上的玩家,他们可以集中在这里频道里,然后可以通过这个频道,给这些位于不同进程上的玩家发送信息。

1)channelRemote.js

给玩家发消息推送机制pushMessage

Remote.prototype.pushMessage = function(route, msg, uids, opts, cb) {
  if(!msg){
    logger.error('Can not send empty message! route : %j, compressed msg : %j',
        route, msg);
    utils.invokeCallback(cb, new Error('can not send empty message.'));
    return;
  }
  
  var connector = this.app.components.__connector__;

  var sessionService = this.app.get('sessionService');
  var fails = [], sids = [], sessions, j, k;
  for(var i=0, l=uids.length; i<l; i++) {
    sessions = sessionService.getByUid(uids[i]);
    if(!sessions) {
      fails.push(uids[i]);
    } else {
      for(j=0, k=sessions.length; j<k; j++) {
        sids.push(sessions[j].id);
      }
    }
  }
  logger.debug('[%s] pushMessage uids: %j, msg: %j, sids: %j', this.app.serverId, uids, msg, sids);
  connector.send(null, route, msg, sids, opts, function(err) {
    utils.invokeCallback(cb, err, fails);
  });
};

可见,通过channelService给玩家发送消息的话,其实是要循环一遍,根据玩家所在的服务器等信息,发给他们,就好像这些玩家在一个服务器上一样,这就是分布式的概念。

2)channelService的使用

this.channelService = app.get('channelService');

var channel = this.channelService.getChannel(rid, false);
if(!!channel){
    channel.leave(uid, sid);
}

var param = {
    route: 'onUserList',
    userList: this.get(rid, false)
};

channel.pushMessage(param);

因此channelService是通过get得到,那么肯定有set的地方channelRemote.js

app.set('sessionService', sessionService);

猜你喜欢

转载自blog.csdn.net/themagickeyjianan/article/details/88784543