Below is a very minimal gRPC Server in NodeJS.
greeter_server.js
var PROTO_PATH = __dirname '/../../protos/helloworld.proto';
var grpc = require('@grpc/grpc-js');
var protoLoader = require('@grpc/proto-loader');
var packageDefinition = protoLoader.loadSync(
PROTO_PATH,
{keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
});
var hello_proto = grpc.loadPackageDefinition(packageDefinition).helloworld;
function sayHello(call, callback) {
callback(null, {message: 'Hello ' call.request.name});
}
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();
});
}
main();
I was able to host the above server in Cloud Run and I was given a url to access the server which is of the form https://greeter-service-abcdefghij-ue.a.run.app.
Below is a client to connect to the server above.
greeter_client.js
var PROTO_PATH = __dirname '/../../protos/helloworld.proto';
var parseArgs = require('minimist');
var grpc = require('@grpc/grpc-js');
var protoLoader = require('@grpc/proto-loader');
var packageDefinition = protoLoader.loadSync(
PROTO_PATH,
{keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
});
var hello_proto = grpc.loadPackageDefinition(packageDefinition).helloworld;
function main() {
var target = 'localhost:50051'; //If I change this to greeter-service-abcdefghij-ue.a.run.app I get an error
var client = new hello_proto.Greeter(target,
grpc.credentials.createInsecure());
var user='world';
client.sayHello({name: user}, function(err, response) {
console.log('Greeting:', response.message);
});
}
main();
Everything works perfectly if I am running both the server and client on localhost but the moment I change the clients connection address from localhost:50051
to greeter-service-abcdefghij-ue.a.run.app
I get the following error:
Error: 14 UNAVAILABLE: read ECONNRESET
Is there a specific way to connect to the server when it has been hosted?
Thank you
CodePudding user response:
One possible problem is that you are not binding the server to the right port. The Cloud Run documentation says
The only special requirement for a gRPC server running in Cloud Run is to listen at the port specified by the
PORT
environment variable