python程序作为服务端,Go程序作为客户端,基于gPRC进行通信
客户端
定义proto文件:
syntax = "proto3";
option go_package = ".;transfer";
service Greeter {
rpc SendImage (ImageRequest) returns (ImageReply) {}
}
message ImageRequest {
string name = 1;
bytes image = 2;
}
message ImageReply {
string message = 1;
}
编译: protoc --go_out=. --go-grpc_out=. ./*.proto
调用:
package main
import (
"context"
"google.golang.org/grpc"
"io/ioutil"
"log"
"time"
"vtion/transfer"
)
const (
address = "localhost:50051"
name = "test"
)
func main() {
conn, err := grpc.Dial(address, grpc.WithInsecure())
if err != nil {
log.Fatalf("connect error: %v", err.Error())
}
defer conn.Close()
client := transfer.NewGreeterClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
image, err := ioutil.ReadFile("./images/binary.jpg")
if err != nil {
log.Fatalf("read error: %v", err.Error())
}
res, err := client.SendImage(ctx, &transfer.ImageRequest{Name: name, Image: image})
if err != nil {
log.Fatalf("send error: %v", err.Error())
}
log.Println(res.Message)
}
服务端
proto文件:
syntax = "proto3";
service Greeter {
rpc SendImage (ImageRequest) returns (ImageReply) {}
}
message ImageRequest {
string name = 1;
bytes image = 2;
}
message ImageReply {
string message = 1;
}
编译: python3 -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. transfer.proto
调用:
from concurrent import futures
from PIL import Image
import time, logging, grpc, io
import transfer_pb2
import transfer_pb2_grpc
class Greeter(transfer_pb2_grpc.GreeterServicer):
def SendImage(self, request, context):
stream = request.image
data = io.BytesIO(stream)
image = Image.open(data)
image.save("test.png")
return transfer_pb2.ImageReply(message=f"success {request.name}")
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
transfer_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port("[::]:50051")
server.start()
server.wait_for_termination()
if __name__ == "__main__":
serve()
标签:err,Python,transfer,image,server,gRPC,Go,message,grpc
From: https://www.cnblogs.com/N3ptune/p/16996047.html