1. 定义 .proto
文件
首先,创建一个 .proto
文件,定义服务和消息:
syntax = "proto3";
package helloworld;
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
### 2. 实现服务器
创建 `greeter_server.js` 文件,包含服务的实现:
```javascript
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');
const packageDefinition = protoLoader.loadSync('helloworld.proto', {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
});
const helloProto = grpc.loadPackageDefinition(packageDefinition).helloworld;
function sayHello(call, callback) {
callback(null, { message: 'Hello ' + call.request.name });
}
function sayHelloAgain(call, callback) {
callback(null, { message: 'Hello again, ' + call.request.name });
}
function main() {
const server = new grpc.Server();
server.addService(helloProto.Greeter.service, { sayHello: sayHello, sayHelloAgain: sayHelloAgain });
server.bindAsync('0.0.0.0:50051', grpc.ServerCredentials.createInsecure(), () => {
server.start();
});
}
main();
3. 实现客户端
创建 greeter_client.js
文件,包含客户端的实现:
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');
const packageDefinition = protoLoader.loadSync('helloworld.proto', {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
});
const helloProto = grpc.loadPackageDefinition(packageDefinition).helloworld;
function main() {
const client = new helloProto.Greeter('localhost:50051', grpc.credentials.createInsecure());
client.sayHello({ name: 'World' }, (err, response) => {
if (err) console.error(err);
else console.log('Greeting:', response.message);
});
client.sayHelloAgain({ name: 'World' }, (err, response) => {
if (err) console.error(err);
else console.log('Greeting:', response.message);
});
}
main();
4. 运行服务器和客户端
确保你已经安装了所有必要的依赖:
npm install @grpc/grpc-js @grpc/proto-loader
然后,分别运行服务器和客户端:
node greeter_server.js
node greeter_client.js