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()

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/272783.html

(0)
上一篇 2022年7月9日 11:52
下一篇 2022年7月9日

相关推荐

发表回复

登录后才能评论