1.proto
syntax = "proto3";
option go_package = ".;proto";
//The greeting service definition
service Greeter{
//Sends a greeting
rpc SayHello(HelloRequest) returns (HelloReply);
}
//The request message containing the user's name.
message HelloRequest{
string name = 1;
}
//The response message containing the greetings
message HelloReply{
string message = 1;
}
2.server
from __future__ import print_function
from concurrent import futures
import logging
import grpc
import helloworld_pb2
import helloworld_pb2_grpc
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
for key, value in context.invocation_metadata():
print('Received initial metadata: key=%s value=%s' % (key, value))
return helloworld_pb2.HelloReply(message='Hello,%s!' % request.name)
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port('[::]:50051')
server.start()
server.wait_for_termination()
if __name__ == '__main__':
logging.basicConfig()
serve()
3.client
from __future__ import print_function
import logging
import grpc
import helloworld_pb2
import helloworld_pb2_grpc
def run():
# NOTE(gRPC Python Team): .close() is possible on a channel and should be
# used in circumstances in which the with statement does not fit the needs
# of the code.
with grpc.insecure_channel('localhost:50051') as channel:
stub = helloworld_pb2_grpc.GreeterStub(channel)
response, call = stub.SayHello.with_call(
helloworld_pb2.HelloRequest(name='you'),
metadata=(
('name', 'golang'),
('password', 'jetbrains')
)
)
print("Greeter client received: " + response.message)
if __name__ == '__main__':
run()