go实现grpc通信
温馨提示:
本文最后更新于 2022年04月22日,已超过 881 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我。
准备环境
go get google.golang.org/grpc
go get google.golang.org/protobuf
代码实现
新增 chat/chat.proto 文件:
syntax = "proto3";
package template;
option go_package = "../chat";
message Message{
string body = 1;
}
service ChatService{
rpc SayHello(Message) returns (Message){}
rpc BroadcastMessage2(Message) returns (Message) {}
}
命令生成pb.go
protoc --go_out=plugins=grpc:chat ./chat/chat.proto
编写chat 服务文件 chat.go:
package chat
import (
"context"
"log"
)
type Server struct {
}
func (receiver \*Server) SayHello(ctx context.Context, in \*Message) (*Message, error) {
log.Printf("Receive message body from client: %s", in.Body)
return &Message{Body: "Hello From the Server!"}, nil
}
func (receiver \*Server) Test(ctx context.Context, in \*Message) (*Message, error) {
log.Printf("test new message from a client: %s", in.Body)
return &Message{Body: "test message!"}, nil
}
编写grpc-server服务端:
package main
import (
"fmt"
"google.golang.org/grpc"
"grpc-study/chat"
"log"
"net"
)
func main() {
fmt.Println("Go gRPC Beginners Tutorial!")
listen, err := net.Listen("tcp", ":9000")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
grpcServer := grpc.NewServer()
s := chat.Server{}
chat.RegisterChatServiceServer(grpcServer, &s)
if err := grpcServer.Serve(listen); err != nil {
log.Fatalf("failed to serve: %s", err)
}
}
grpc-client 客户端调用
package main
import (
"context"
"google.golang.org/grpc"
"grpc-study/chat"
"log"
"time"
)
func main() {
var conn *grpc.ClientConn
conn, err := grpc.Dial(":9000", grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %s \n", err)
}
defer conn.Close()
c := chat.NewChatServiceClient(conn)
for true {
response, err := c.SayHello(context.Background(), &chat.Message{Body: "66666"})
if err != nil {
log.Fatalf("Error when calling SayHello: %s", err)
}
log.Printf("Response from server: %s", response.Body)
broadcastMessage, err := c.Test(context.Background(), &chat.Message{Body: "123"})
if err != nil {
log.Fatalf("Error when calling Broadcast Message: %s", err)
}
log.Printf("Response from server: %s", broadcastMessage.Body)
time.Sleep(1*time.Second)
}
}
启动
正文到此结束
- 本文标签: 编程语言
- 本文链接: https://www.php20.cn/article/365
- 版权声明: 本文由仙士可原创发布,转载请遵循《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权