01 Setting Up gRPC
RPC is short for Remote Procedure Call.
Put simply, it lets you call a remote method as though it were local.
gRPC is a high-performance, general-purpose, open-source RPC framework developed by Google.
Environment Preparation
On Windows, install the protoc compiler.
https://github.com/protocolbuffers/protobuf/releases/tag/v3.9.0
https://github.com/protocolbuffers/protobuf/releases/download/v3.9.0/protoc-3.9.0-win64.zip
// 都需要安装的依赖
go get github.com/golang/protobuf/proto
go get google.golang.org/grpc
go install github.com/golang/protobuf/protoc-gen-go
After installation, add the protoc bin directory to your environment variables.
Also add the directory containing protoc-gen-go.exe to your environment variables.
After adding them, you may need to restart the computer or GoLand before they can be used in GoLand's terminal.
Writing a Protobuf File
Do not worry if you have not yet learned how to write one; copy and paste it for now.
It is mainly used to verify that the environment works correctly.
syntax = "proto3"; // 指定proto版本
package hello_grpc; // 指定默认包名
// 指定golang包名
option go_package = "/hello_grpc";
//定义rpc服务
service HelloService {
// 定义函数
rpc SayHello (HelloRequest) returns (HelloResponse) {}
}
// HelloRequest 请求内容
message HelloRequest {
string name = 1;
string message = 2;
}
// HelloResponse 响应内容
message HelloResponse{
string name = 1;
string message = 2;
}
Pay attention to my path
Execute under grpc path
Generate go files through protobuf
// protoc -I . --go_out=plugins=grpc:. .\hello.proto
Or in the project root directory
// protoc -I . --go_out=plugins=grpc:.\grpc .\grpc\hello.proto
If this file is generated, congratulations, the environmental problem that stumps 50% of people has been solved.
02 Native Go RPC
Server
package main
import (
"fmt"
"net"
"net/http"
"net/rpc"
)
type Server struct {
}
type Req struct {
Num1 int
Num2 int
}
type Res struct {
Num int
}
func (s Server) Add(req Req, res *Res) error {
res.Num = req.Num1 + req.Num2
return nil
}
func main() {
// 注册rpc服务
rpc.Register(new(Server))
rpc.HandleHTTP()
listen, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Println(err)
return
}
http.Serve(listen, nil)
}
Client
package main
import (
"fmt"
"net/rpc"
)
type Req struct {
Num1 int
Num2 int
}
type Res struct {
Num int
}
func main() {
req := Req{1, 2}
client, err := rpc.DialHTTP("tcp", ":8080")
if err != nil {
fmt.Println(err)
return
}
var res Res
client.Call("Server.Add", req, &res)
fmt.Println(res)
}
Problems with native RPC:
- It is relatively complex to write and requires attention to implementation details.
- There is no code completion, so mistakes are easy to make.
03 Write a gRPC Hello World
Write the Protobuf File
syntax = "proto3"; // 指定proto版本
package hello_grpc; // 指定默认包名
// 指定golang包名
option go_package = "/hello_grpc";
//定义rpc服务
service HelloService {
// 定义函数
rpc SayHello (HelloRequest) returns (HelloResponse) {}
}
// HelloRequest 请求内容
message HelloRequest {
string name = 1;
string message = 2;
}
// HelloResponse 响应内容
message HelloResponse{
string name = 1;
string message = 2;
}
If .proto files are not highlighted, install a gRPC plugin.

Run this in the grpc_proto directory:
protoc -I . --go_out=plugins=grpc:. .\hello.proto
Or run this from the project root:
protoc -I . --go_out=plugins=grpc:.\grpc_proto .\grpc_proto\hello.proto

You can create a batch file to make conversion easier.
set.bat
protoc -I . --go_out=plugins=grpc:.\grpc_proto .\grpc_proto\hello.proto

Server
- Write a struct; its name does not matter.
- The important part is implementing every method in the Protobuf definition.
- Listen on a port.
- Register the service.
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/grpclog"
"grpc_study/grpc_proto/hello_grpc"
"net"
)
// HelloServer1 得有一个结构体,需要实现这个服务的全部方法,叫什么名字不重要
type HelloServer1 struct {
}
func (HelloServer1) SayHello(ctx context.Context, request *hello_grpc.HelloRequest) (pd *hello_grpc.HelloResponse, err error) {
fmt.Println("入参:", request.Name, request.Message)
pd = new(hello_grpc.HelloResponse)
pd.Name = "你好"
pd.Message = "ok"
return
}
func main() {
// 监听端口
listen, err := net.Listen("tcp", ":8080")
if err != nil {
grpclog.Fatalf("Failed to listen: %v", err)
}
// 创建一个gRPC服务器实例。
s := grpc.NewServer()
server := HelloServer1{}
// 将server结构体注册为gRPC服务。
hello_grpc.RegisterHelloServiceServer(s, &server)
fmt.Println("grpc server running :8080")
// 开始处理客户端请求。
err = s.Serve(listen)
}

Client
- Establish a connection.
- Call a method.
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"grpc_study/grpc_proto/hello_grpc"
"log"
)
func main() {
addr := ":8080"
// 使用 grpc.Dial 创建一个到指定地址的 gRPC 连接。
// 此处使用不安全的证书来实现 SSL/TLS 连接
conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf(fmt.Sprintf("grpc connect addr [%s] 连接失败 %s", addr, err))
}
defer conn.Close()
// 初始化客户端
client := hello_grpc.NewHelloServiceClient(conn)
result, err := client.SayHello(context.Background(), &hello_grpc.HelloRequest{
Name: "枫枫",
Message: "ok",
})
fmt.Println(result, err)
}
If you need to use this connection object often, reuse it.
func initClient() hello_grpc.HelloServiceClient {
addr := ":8080"
conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf(fmt.Sprintf("grpc connect addr [%s] 连接失败 %s", addr, err))
}
client := hello_grpc.NewHelloServiceClient(conn)
return client
}
func main() {
client := initClient()
result, err := client.SayHello(context.Background(), &hello_grpc.HelloRequest{
Name: "枫枫",
Message: "ok",
})
result, err = client.SayHello(context.Background(), &hello_grpc.HelloRequest{
Name: "哈哈哈",
Message: "ok1",
})
fmt.Println(result, err)
}
04 gRPC Proto Files
syntax = "proto3"; // 指定proto版本
package hello_grpc; // 指定默认包名
// 指定golang包名
option go_package = "/hello_grpc";
//定义rpc服务
service HelloService {
// 定义函数
rpc SayHello (HelloRequest) returns (HelloResponse) {}
}
// HelloRequest 请求内容
message HelloRequest {
string name = 1; // 消息号
string message = 2;
}
// HelloResponse 响应内容
message HelloResponse{
string name = 1;
string message = 2;
}
Generate Go Files
option go_package = ".;xxx";
go_package means that the Go file is generated in the current directory and its package name is xxx.
protoc -I . --go_out=plugins=grpc:./grpc_proto .\grpc_proto\hello.proto
The .proto file only defines interface methods.
Proto Syntax
service corresponds to a Go interface and can be used by both the server and client.
rpc corresponds to a method on a struct.
message also corresponds to a struct.
Data Types
Basic Data Types
message Request {
double a1 = 1;
float a2 = 2;
int32 a3 = 3;
uint32 a4 = 4;
uint64 a5 = 5;
sint32 a6 = 6;
sint64 a7 = 7;
fixed32 a8 = 8;
fixed64 a9 = 9;
sfixed32 a10 = 10;
sfixed64 a11 = 11;
bool a12 = 12;
string a13 = 13;
bytes a14 = 14;
}
Corresponding Go types
type Request struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
A1 float64 `protobuf:"fixed64,1,opt,name=a1,proto3" json:"a1,omitempty"`
A2 float32 `protobuf:"fixed32,2,opt,name=a2,proto3" json:"a2,omitempty"`
A3 int32 `protobuf:"varint,3,opt,name=a3,proto3" json:"a3,omitempty"`
A4 uint32 `protobuf:"varint,4,opt,name=a4,proto3" json:"a4,omitempty"`
A5 uint64 `protobuf:"varint,5,opt,name=a5,proto3" json:"a5,omitempty"`
A6 int32 `protobuf:"zigzag32,6,opt,name=a6,proto3" json:"a6,omitempty"`
A7 int64 `protobuf:"zigzag64,7,opt,name=a7,proto3" json:"a7,omitempty"`
A8 uint32 `protobuf:"fixed32,8,opt,name=a8,proto3" json:"a8,omitempty"`
A9 uint64 `protobuf:"fixed64,9,opt,name=a9,proto3" json:"a9,omitempty"`
A10 int32 `protobuf:"fixed32,10,opt,name=a10,proto3" json:"a10,omitempty"`
A11 int64 `protobuf:"fixed64,11,opt,name=a11,proto3" json:"a11,omitempty"`
A12 bool `protobuf:"varint,12,opt,name=a12,proto3" json:"a12,omitempty"`
A13 string `protobuf:"bytes,13,opt,name=a13,proto3" json:"a13,omitempty"`
A14 []byte `protobuf:"bytes,14,opt,name=a14,proto3" json:"a14,omitempty"`
}
Scalar types
| .proto Type | Explanation | Go Type |
|---|---|---|
| double | float64 | |
| float | float32 | |
| int32 | Use variable-length encoding, which is inefficient for negative values. If your field may have negative values, please use sint64 instead | int32 |
| uint32 | Use variable length encoding | uint32 |
| uint64 | Use variable length encoding | uint64 |
| sint32 | Use variable length encodings, these encodings are much more efficient than int32 for negative values | int32 |
| sint64 | A signed integer value using variable-length encoding. Efficient when encoding than usual int64 | int64 |
| fixed32 | Always 4 bytes, this type will be more efficient than uint32 if the value is always greater than 228. | uint32 |
| fixed64 | Always 8 bytes, this type will be more efficient than uint64 if the value is always greater than 256. | uint64 |
| sfixed32 | always 4 bytes | int32 |
| sfixed64 | always 8 bytes | int64 |
| bool | bool | |
| string | A string must be UTF-8 encoded or 7-bit ASCII encoded text | string |
| bytes | May contain byte data in any order | []byte |
If a scalar type is not assigned, it is not serialized. When parsed, it receives a default value:
- strings: empty string
- bytes: empty sequence
- booleans:
false - numeric types:
0
Array Types
message ArrayRequest {
repeated int64 a1 = 1;
repeated string a2 = 2;
repeated Request request_list = 3;
}
Go type
type ArrayRequest struct {
A1 []int64
A2 []string
RequestList []*Request
}
Map Types
Keys can only use basic types.
message MapRequest {
map<int64, string> m_i_s = 1;
map<string, bool> m_i_b = 2;
map<string, ArrayRequest> m_i_arr = 3;
}
Go type
type MapRequest struct {
MIS map[int64]string
MIB map[string]bool
MIArr map[string]*ArrayRequest
}
Nested Types
message Q1 {
message Q2{
string name2 = 2;
}
string name1 = 1;
Q2 q2 = 2;
}
type Q1 struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Name1 string `protobuf:"bytes,1,opt,name=name1,proto3" json:"name1,omitempty"`
Q2 *Q1_Q2 `protobuf:"bytes,2,opt,name=q2,proto3" json:"q2,omitempty"`
}
Style Guide
- Use underscores in filenames, for example
my_student.proto. - Match the package name to the directory name.
- Use PascalCase for service, method, and message names.
- Use underscores in field names.
Multiple Services
syntax = "proto3"; // 指定proto版本
// 指定golang包名
option go_package = "/duo_proto";
service VideoService {
rpc Look(Request)returns(Response){}
}
message Request{
string name = 1;
}
message Response{
string name = 1;
}
service OrderService {
rpc Buy(Request)returns(Response){}
}
Server
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"grpc_study/grpc_proto/duo_proto"
"log"
"net"
)
type VideoServer struct {
}
func (VideoServer) Look(ctx context.Context, request *duo_proto.Request) (res *duo_proto.Response, err error) {
fmt.Println("video:", request)
return &duo_proto.Response{
Name: "fengfeng",
}, nil
}
type OrderServer struct {
}
func (OrderServer) Buy(ctx context.Context, request *duo_proto.Request) (res *duo_proto.Response, err error) {
fmt.Println("order:", request)
return &duo_proto.Response{
Name: "fengfeng",
}, nil
}
func main() {
listen, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatal(err)
}
s := grpc.NewServer()
duo_proto.RegisterVideoServiceServer(s, &VideoServer{})
duo_proto.RegisterOrderServiceServer(s, &OrderServer{})
fmt.Println("grpc server程序运行在:8080")
err = s.Serve(listen)
}
Client
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"grpc_study/grpc_proto/duo_proto"
"log"
)
func main() {
addr := ":8080"
// 使用 grpc.Dial 创建一个到指定地址的 gRPC 连接。
// 此处使用不安全的证书来实现 SSL/TLS 连接
conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf(fmt.Sprintf("grpc connect addr [%s] 连接失败 %s", addr, err))
}
defer conn.Close()
orderClient := duo_proto.NewOrderServiceClient(conn)
res, err := orderClient.Buy(context.Background(), &duo_proto.Request{
Name: "枫枫",
})
fmt.Println(res, err)
videoClient := duo_proto.NewVideoServiceClient(conn)
res, err = videoClient.Look(context.Background(), &duo_proto.Request{
Name: "枫枫",
})
fmt.Println(res, err)
}
Multiple Proto Files
As a project grows, it will have many services, RPCs, and messages.
Put different services in separate .proto files.
You can also add shared .proto files.
Reliable documentation on this topic is surprisingly scarce.
At its core, it is about generating Go files that belong to one package.

video.proto
syntax = "proto3";
package proto1;
option go_package = "/proto";
import "common.proto";
service VideoService {
rpc Look(Request)returns(Response){}
}
order.proto
syntax = "proto3";
package proto;
option go_package = "/proto";
import "common.proto";
service OrderService {
rpc Look(Request)returns(Response){}
}
common.proto
syntax = "proto3";
package proto;
option go_package = "/proto";
message Request{
string name = 1;
}
message Response{
string name = 1;
}
Generation commands
protoc -I .\service_proto --go_out=plugins=grpc:./service_proto .\service_proto\order.proto
protoc -I .\service_proto --go_out=plugins=grpc:./service_proto .\service_proto\video.proto
protoc -I .\service_proto --go_out=plugins=grpc:./service_proto .\service_proto\common.proto
There are a few points to note.
If there is an import, you must declare a package,
and it must match the imported package.
05 gRPC Streaming
Unary RPC
One request, one response.
syntax = "proto3";
option go_package = "/proto";
service Simple {
rpc Fun(Request)returns(Response){}
}
message Request {
string name = 1;
}
message Response {
string Text = 1;
}
The server and client code are the same as in the previous section.
Server Streaming
Server
package main
import (
"fmt"
"google.golang.org/grpc"
"grpc_study/stream_proto/proto"
"log"
"net"
)
type ServiceStream struct{}
func (ServiceStream) Fun(request *proto.Request, stream proto.ServiceStream_FunServer) error {
fmt.Println(request)
for i := 0; i < 10; i++ {
stream.Send(&proto.Response{
Text: fmt.Sprintf("第%d轮数据", i),
})
}
return nil
}
func main() {
listen, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatal(err)
}
server := grpc.NewServer()
proto.RegisterServiceStreamServer(server, &ServiceStream{})
server.Serve(listen)
}
Client
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"grpc_study/stream_proto/proto"
"log"
)
func main() {
addr := ":8080"
// 使用 grpc.Dial 创建一个到指定地址的 gRPC 连接。
// 此处使用不安全的证书来实现 SSL/TLS 连接
conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf(fmt.Sprintf("grpc connect addr [%s] 连接失败 %s", addr, err))
}
defer conn.Close()
// 初始化客户端
client := proto.NewServiceStreamClient(conn)
stream, err := client.Fun(context.Background(), &proto.Request{
Name: "张三",
})
for i := 0; i < 10; i++ {
response, err := stream.Recv()
fmt.Println(response, err)
}
}
The Client Does Not Know When the Server Ends
stream, err := client.Fun(context.Background(), &proto.Request{
Name: "张三",
})
for {
response, err := stream.Recv()
if err == io.EOF {
break
}
fmt.Println(response)
}
Download a File
Proto file
syntax = "proto3";
option go_package = "/proto";
message Request {
string name = 1;
}
message FileResponse{
string file_name = 1;
bytes content = 2;
}
service ServiceStream{
rpc DownLoadFile(Request)returns(stream FileResponse){}
}
// protoc -I . --go_out=plugins=grpc:./stream_proto .\stream_proto\stream.proto
Server
package main
import (
"fmt"
"google.golang.org/grpc"
"grpc_study/stream_proto/proto"
"io"
"log"
"net"
"os"
)
type ServiceStream struct{}
func (ServiceStream) DownLoadFile(request *proto.Request, stream proto.ServiceStream_DownLoadFileServer) error {
fmt.Println(request)
file, err := os.Open("static/1.gvb_web项目搭建.mp4")
if err != nil {
return err
}
defer file.Close()
for {
buf := make([]byte, 2048)
_, err = file.Read(buf)
if err == io.EOF {
break
}
if err != nil {
break
}
stream.Send(&proto.FileResponse{
Content: buf,
})
}
return nil
}
func main() {
listen, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatal(err)
}
server := grpc.NewServer()
proto.RegisterServiceStreamServer(server, &ServiceStream{})
server.Serve(listen)
}
Client
package main
import (
"bufio"
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"grpc_study/stream_proto/proto"
"io"
"log"
"os"
)
func main() {
addr := ":8080"
// 使用 grpc.Dial 创建一个到指定地址的 gRPC 连接。
// 此处使用不安全的证书来实现 SSL/TLS 连接
conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf(fmt.Sprintf("grpc connect addr [%s] 连接失败 %s", addr, err))
}
defer conn.Close()
// 初始化客户端
client := proto.NewServiceStreamClient(conn)
stream, err := client.DownLoadFile(context.Background(), &proto.Request{
Name: "张三",
})
file, err := os.OpenFile("static/1.gvb_web项目搭建1.mp4", os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
log.Fatalln(err)
}
defer file.Close()
writer := bufio.NewWriter(file)
var index int
for {
index++
response, err := stream.Recv()
if err == io.EOF {
break
}
fmt.Printf("第%d 次, 写入 %d 数据\n", index, len(response.Content))
writer.Write(response.Content)
}
writer.Flush()
}
Client Streaming
Proto
syntax = "proto3";
option go_package = "/proto";
message Response {
string Text = 1;
}
message FileRequest{
string file_name = 1;
bytes content = 2;
}
service ClientStream{
rpc UploadFile(stream FileRequest)returns(Response){}
}
Server
package main
import (
"fmt"
"google.golang.org/grpc"
"grpc_study/stream_proto/proto"
"log"
"net"
)
type ClientStream struct{}
func (ClientStream) UploadFile(stream proto.ClientStream_UploadFileServer) error {
for i := 0; i < 10; i++ {
response, err := stream.Recv()
fmt.Println(response, err)
}
stream.SendAndClose(&proto.Response{Text: "完毕了"})
return nil
}
func main() {
listen, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatal(err)
}
server := grpc.NewServer()
proto.RegisterClientStreamServer(server, &ClientStream{})
server.Serve(listen)
}
Client
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"grpc_study/stream_proto/proto"
"log"
)
func main() {
addr := ":8080"
conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf(fmt.Sprintf("grpc connect addr [%s] 连接失败 %s", addr, err))
}
defer conn.Close()
// 初始化客户端
client := proto.NewClientStreamClient(conn)
stream, err := client.UploadFile(context.Background())
for i := 0; i < 10; i++ {
stream.Send(&proto.FileRequest{FileName: fmt.Sprintf("第%d次", i)})
}
response, err := stream.CloseAndRecv()
fmt.Println(response, err)
}
Upload a File
Server
package main
import (
"bufio"
"fmt"
"google.golang.org/grpc"
"grpc_study/stream_proto/proto"
"io"
"log"
"net"
"os"
)
type ClientStream struct{}
func (ClientStream) UploadFile(stream proto.ClientStream_UploadFileServer) error {
file, err := os.OpenFile("static/x.png", os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
log.Fatalln(err)
}
defer file.Close()
writer := bufio.NewWriter(file)
var index int
for {
index++
response, err := stream.Recv()
if err == io.EOF {
break
}
writer.Write(response.Content)
fmt.Printf("第%d次", index)
}
writer.Flush()
stream.SendAndClose(&proto.Response{Text: "完毕了"})
return nil
}
func main() {
listen, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatal(err)
}
server := grpc.NewServer()
proto.RegisterClientStreamServer(server, &ClientStream{})
server.Serve(listen)
}
Client
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"grpc_study/stream_proto/proto"
"io"
"log"
"os"
)
func main() {
addr := ":8080"
// 使用 grpc.Dial 创建一个到指定地址的 gRPC 连接。
// 此处使用不安全的证书来实现 SSL/TLS 连接
conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf(fmt.Sprintf("grpc connect addr [%s] 连接失败 %s", addr, err))
}
defer conn.Close()
// 初始化客户端
client := proto.NewClientStreamClient(conn)
stream, err := client.UploadFile(context.Background())
file, err := os.Open("static/21.png")
if err != nil {
log.Fatalln(err)
}
defer file.Close()
for {
buf := make([]byte, 2048)
_, err = file.Read(buf)
if err == io.EOF {
break
}
if err != nil {
break
}
stream.Send(&proto.FileRequest{
FileName: "x.png",
Content: buf,
})
}
response, err := stream.CloseAndRecv()
fmt.Println(response, err)
}
Bidirectional Streaming
Proto
syntax = "proto3";
option go_package = "/proto";
message Request {
string name = 1;
}
message Response {
string Text = 1;
}
service BothStream{
rpc Chat(stream Request)returns(stream Response){}
}
Server
package main
import (
"fmt"
"google.golang.org/grpc"
"grpc_study/stream_proto/proto"
"log"
"net"
)
type BothStream struct{}
func (BothStream) Chat(stream proto.BothStream_ChatServer) error {
for i := 0; i < 10; i++ {
request, _ := stream.Recv()
fmt.Println(request)
stream.Send(&proto.Response{
Text: "你好",
})
}
return nil
}
func main() {
listen, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatal(err)
}
server := grpc.NewServer()
proto.RegisterBothStreamServer(server, &BothStream{})
server.Serve(listen)
}
Client
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"grpc_study/stream_proto/proto"
"log"
)
func main() {
addr := ":8080"
// 使用 grpc.Dial 创建一个到指定地址的 gRPC 连接。
// 此处使用不安全的证书来实现 SSL/TLS 连接
conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf(fmt.Sprintf("grpc connect addr [%s] 连接失败 %s", addr, err))
}
defer conn.Close()
// 初始化客户端
client := proto.NewBothStreamClient(conn)
stream, err := client.Chat(context.Background())
for i := 0; i < 10; i++ {
stream.Send(&proto.Request{
Name: fmt.Sprintf("第%d次", i),
})
response, err := stream.Recv()
fmt.Println(response, err)
}
}
syntax = "proto3";
option go_package = "/proto";
service Simple {
rpc Fun(Request)returns(Response){}
}
// 服务端流式
service ServiceStream{
rpc Fun(Request)returns(stream Response){}
rpc DownLoadFile(Request)returns(stream FileResponse){}
}
// 客户端流式
service ClientStream{
rpc UploadFile(stream FileRequest)returns(Response){}
}
// 双向流
service BothStream{
rpc Chat(stream Request)returns(stream Response){}
}
message Request {
string name = 1;
}
message Response {
string Text = 1;
}
message FileRequest{
string file_name = 1;
bytes content = 2;
}
message FileResponse{
string file_name = 1;
bytes content = 2;
}
// protoc -I . --go_out=plugins=grpc:./stream_proto .\stream_proto\stream.proto