• 给Pomelo的聊天室添加time的RPC调用


      为了练手,给聊天应用增加一个rpc调用和一个time类型的服务器,在servers/time/remote/timeRemote.js中,添加如下代码:

    module.exports.getCurrentTime = function (arg1, arg2, cb) {
      console.log("timeRemote - arg1: " + arg1+ "; " + "arg2: " + arg2);
      var d = new Date();
      var hour = d.getHours();
      var min = d.getMinutes();
      var sec = d.getSeconds();
      cb( hour, min, sec);
    };
    

      在gate中调用后console出来:

    // gateHandler.js
    var routeParam = Math.floor(Math.random()*10);
    app.rpc.time.timeRemote.getCurrentTime(routeParam, arg1, arg2,  function(hour, min, sec) {
      // ...
    });
    

      当有多个time服务器的时候,需要在app.js配置route规则:

    var router = function(routeParam, msg, context, cb) {
      var timeServers = app.getServersByType('time');
      var id = timeServers[routeParam % timeServers.length].id;
      cb(null, id);
    }
    
    app.route('time', router);
    

      在服务器配置config/servers.json中增加time服务器如下:

    "time":[
      {"id": "time-server-1", "host":"127.0.0.1", "port" : 7000},
      {"id": "time-server-2", "host":"127.0.0.1", "port" : 7001}
    ]
    

      需要注意的是,有两个导出方式,即导出对象和函数

    module.exports = function(app) {
        return new ChatRemote(app);
    };
    
    // timeRemote.js
    module.exports.getCurrentTime(arg1, arg2, cb) {
      // ...
    };
    

      对于当前端服务器接受客户端请求,将请求路由给后端服务器时,pomelo使用的是发起一个系统级远程调用的方式,这个时候会使用session作为rpc请求的路由参数,这也是我们看到的前面在给chat配置路由的时候,路由函数的第一个参数总是session。在time中,我们使用了一个随机整数作为路由参数,因此time的路由函数的第一个参数也就是这个随机整数了。实际上pomelo的rpc框架对于路由参数的使用是没有限制的,并不仅限于一直使用session。

      0.8版本以后,当进行rpc调用的时候,可以跳过路由计算而直接将调用发送到一个具体的服务器或者广播到一类服务器的调用方式,代码示例如下:

    // route
    var routeParam = session;
    app.rpc.area.playerRemote.leaveTeam(routeParam, args..., cb); //根据routeParam来进行路由计算
    
    // to specified server 'area-server-1'
    app.rpc.area.playerRemote.leaveTeam.toServer('area-server-1', args..., cb); //直接指定路由
    
    // broadcast to all the area servers
    app.rpc.area.playerRemote.leaveTeam.toServer('*', args..., cb); //指定所有的路由
    

      

  • 相关阅读:
    "use strict"
    jquery.is()
    $.proxy
    windows检测文件夹是否更新.bat脚本 windows循环检查文件夹
    linux下串口多线程通信 ,多串口收发数据错乱问题解决办法
    linux串口配置详解
    linux socket 程序被ctrl+c或者异常终止,提示:bind error:Address already in use,解决办法
    linux下包含自定义.c文件 调用报错未定义解决办法
    linux下对一个文件写完马上读取,读到空白
    linux 下socket通信,client断开service退出解决办法
  • 原文地址:https://www.cnblogs.com/fuland/p/4001040.html
Copyright © 2020-2023  润新知