阿西河

所有教程

公众号
🌙
阿西河前端的公众号

我的收藏

    最近访问  (文章)

      教程列表

      抓包专区
      测试专区

      Node.js rgpc 通信demo

      前置安装

      "@grpc/proto-loader": "^0.1.0",
      "grpc": "^1.11.0",
      

      概念理解

      helloworld.proto

      syntax = "proto3";
      
      package helloworld;
      
      // The greeting service definition.
      service Greeter {
        // Sends a greeting
        rpc SayHello (HelloRequest) returns (HelloReply) {}
      }
      
      // The request message containing the user's name.
      message HelloRequest {
        string name = 1;
      }
      
      // The response message containing the greetings
      message HelloReply {
        string message = 1;
      }
      

      server

      var grpc = require('grpc');
      var protoLoader = require('@grpc/proto-loader');
      // proto的文件
      var PROTO_PATH = '/Users/anbang/Documents/liansheng/grpc-master/examples/node/protos/helloworld.proto';
      
      var packageDefinition = protoLoader.loadSync(
          PROTO_PATH,
          {keepCase: true,
           longs: String,
           enums: String,
           defaults: true,
           oneofs: true
          });
      var hello_proto = grpc.loadPackageDefinition(packageDefinition).helloworld;
      
      /**
       * 实现RPC方法
       */
      function sayHello(call, callback) {
        callback(null, {message: 'Hello ' + call.request.name});
      }
      
      /**
       * Starts an RPC server that receives requests for the Greeter service at the
       * sample server port
       */
      function main() {
        var server = new grpc.Server();
        let options = {
          sayHello: sayHello
        }
        server.addService(hello_proto.Greeter.service, options);
        server.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure());
        server.start();
      }
      main();
      

      client

      var grpc = require('grpc');
      var protoLoader = require('@grpc/proto-loader');
      // proto的文件
      var PROTO_PATH = '/Users/anbang/Documents/liansheng/grpc-master/examples/node/protos/helloworld.proto';
      var packageDefinition = protoLoader.loadSync(
          PROTO_PATH,
          {keepCase: true,
           longs: String,
           enums: String,
           defaults: true,
           oneofs: true
          });
      var hello_proto = grpc.loadPackageDefinition(packageDefinition).helloworld;
      var client = new hello_proto.Greeter('0.0.0.0:50051', grpc.credentials.createInsecure());
      
      function main() {
        // var client = new hello_proto.Greeter('0.0.0.0:50051', grpc.credentials.createInsecure());
        var user;
        if (process.argv.length >= 3) {
          user = process.argv[2];
        } else {
          user = 'world';
        }
        client.sayHello({name: user}, function(err, response) {
          console.log('Greeting:', response);
        });
      }
      
      main();
      

      启动

      分别启动server 和client即可;

      目录
      目录