本文主要是介绍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()
这篇关于nodeJs grpc的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!