Nodejs 版本
Github地址:https://github.com/changbaihe/GrpcDemo
一、编写pb文件(.proto),例:chat.proto
注:1.protocol buffers 维基百科:https://zh.wikipedia.org/wiki/Protocol_Buffers
2.protocol buffers 语法详见:https://developers.google.com/protocol-buffers
syntax = "proto3"; // 使用proto3语法,因为从3.0.0 Beta2版,开始支持JavaScript package grpcTest; // 定义包名 // 定义服务名 service chat { // 定义远程调用方法 rpc getMessage(HelloRequest) returns (HelloResponse) {} rpc getAge(HelloRequest) returns (HelloResponse) {} } // 定义消息类型 message HelloRequest{ int32 id = 1; string name = 2; int32 age = 3; string year = 4; } // 定义消息类型 message HelloResponse{ string reply = 1; }
二、demo代码:index.js
const path = require('path'); const grpc = require('grpc'); const PROTO_PATH = path.join(__dirname,'./chat.proto'); const protoLoader = require('@grpc/proto-loader'); const packageDefinition = protoLoader.loadSync( PROTO_PATH, { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true } ); const protoDescriptor = grpc.loadPackageDefinition(packageDefinition); const packageObj = protoDescriptor.grpcTest; // 服务端 const server = new grpc.Server(); server.addService( packageObj.chat.service, { getMessage: (call, callback) => callback(null, {reply: `hello, ${call.request.name}`}), getAge: (call, callback) => callback(null, {reply: `${call.request.name} age is ${call.request.age} year old.`}), } ); server.bind('0.0.0.0:8080', grpc.ServerCredentials.createInsecure()); server.start(); console.log('servering……'); // 客户端 const client = new packageObj.chat( 'localhost:8080', grpc.credentials.createInsecure() ); setTimeout(() => { const req = { id: 1, name: 'cbh', age: 23, year: '1996' } client.getMessage(req, (err, data) => { if (err) { return console.error(err); } console.log(data.reply); }); client.getAge(req, (err, data) => { if (err) { return console.error(err); } console.log(data.reply); }); }, 1000);