Node.js rgpc 通信demo
   1 分钟阅读

前置安装

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

概念理解

helloworld.proto

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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即可;