nodeJs grpc
node 使用grpc
npm init 创建项目
demo.proto
syntax = "proto3";
package hello;
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string message = 1;
}
message HelloReply {
string message = 1;
}
pb.js
const path = require('path')
const grpc = require('@grpc/grpc-js')
const protoLoader = require('@grpc/proto-loader')
const PROTO_PATH = path.join(__dirname, 'demo.proto')
const packageDefinition = protoLoader.loadSync(PROTO_PATH, { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true })
const protoDescriptor = grpc.loadPackageDefinition(packageDefinition)
const hello_proto = protoDescriptor.hello
module.exports = hello_proto
svc.js
const grpc = require('@grpc/grpc-js')
const hello_proto = require('./proto')
let cnt = 1
function sayHello(call, callback) {
callback(null, { message: `[${cnt++}] echo: ` + call.request.message })
}
function main() {
var server = new grpc.Server()
server.addService(hello_proto.Greeter.service, { sayHello: sayHello })
server.bindAsync('0.0.0.0:50051', grpc.ServerCredentials.createInsecure(), () => {
server.start()
console.log('grpc server started')
})
}
client.js
const hello_proto = require('./proto')
const grpc = require('@grpc/grpc-js')
function main() {
var client = new hello_proto.Greeter('localhost:50051', grpc.credentials.createInsecure())
client.sayHello({ message: 'Hello' }, function(err, response) {
if (err) {
console.error('Error: ', err)
} else {
console.log(response.message)
}
})
}
main()
本文来自博客园,作者:vx_guanchaoguo0,转载请注明原文链接:https://www.cnblogs.com/guanchaoguo/p/16455638.html