Source: org/terraswarm/accessor/accessors/web/grpc/startServerAndClient.js

  1. /** Launcher for gRPC Greeter example.
  2. * This file creates and starts a server providing the service defined
  3. * in the Greeter.proto file. The server listens on port 50051 of the local host.
  4. * It then instantiates a composite accessor defined in the greeterTest.js
  5. * file, which instantiates an accessor that is a Greeter service client.
  6. *
  7. * @authors: Ravi Akella and Edward A. Lee
  8. */
  9. var accessors = require('@terraswarm/accessors');
  10. var grpc = require('grpc');
  11. var protoLoader = require('@grpc/proto-loader');
  12. var util = require('util');
  13. var packageDefinition = protoLoader.loadSync(
  14. './Greeter.proto',
  15. {keepCase: true,
  16. longs: String,
  17. enums: String,
  18. defaults: true,
  19. });
  20. var packageObject = grpc.loadPackageDefinition(packageDefinition);
  21. // Start the server.
  22. var server = new grpc.Server();
  23. server.addService(packageObject.Greeter.service, {sayHello: sayHelloImplementation});
  24. server.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure());
  25. server.start();
  26. console.log('gRPC server started.');
  27. /** Implement the sayHello RPC method of the service. */
  28. function sayHelloImplementation(call, callback) {
  29. console.log('Request from ' + call.getPeer() + ' for sayHello method ' + ' with args ' + util.inspect(call.request));
  30. callback(null, {message: 'Hello ' + call.request.name});
  31. }
  32. // Wait 2 seconds for server to start and then launch the client.
  33. setTimeout(function() {
  34. accessors.processCommandLineArguments(['-timeout', '10000', 'greeterTest.js'], null, null,
  35. function() {
  36. // This function will be invoked when the timeout expires.
  37. server.tryShutdown(function() {
  38. console.log('Server shutting down.');
  39. });
  40. })
  41. }, 2000);