proto文件如下:
syntax = "proto3";
package friday;
// 请求用户信息
message UserInfoRequest {
int64 uid = 1; // 用户ID
}
// 请求用户信息的结果
message UserInfoResponse {
string name = 1; // 用户姓名
uint32 age = 2; // 用户年龄
uint32 sex = 3; // 用户性别
uint32 count = 4; // 账户余额
}
service Data {
//简单Rpc
// 获取用户数据
rpc GetUserInfo(UserInfoRequest) returns (UserInfoResponse){}
// 修改用户 双向流模式
rpc ChangeUserInfo(stream UserInfoResponse) returns (stream UserInfoResponse){}
}
服务端实现:
/*服务端的方法*/
package response
import (
"golang.org/x/net/context"
pb "rpcTest/rpcbuild/rpcbuild/friday"
"fmt"
"io"
)
type Server struct{
routeNotes []*pb.UserInfoResponse
}
//简单模式
func (this *Server)GetUserInfo(ctx context.Context, in *pb.UserInfoRequest)(*pb.UserInfoResponse,error){
uid := in.GetUid()
fmt.Println("The uid is ",uid)
return &pb.UserInfoResponse{
Name : "Jim",
Age : 18,
Sex : 0,
Count:1000,
},nil
}
//双向流模式
func (this *Server) ChangeUserInfo(stream pb.Data_ChangeUserInfoServer)(error){
for {
in, err := stream.Recv()
if err == io.EOF {
fmt.Println("read done")
return nil
}
if err != nil {
fmt.Println("ERR",err)
return err
}
fmt.Println("userinfo ",in)
for _, note := range this.routeNotes{
if err := stream.Send(note); err != nil {
return err
}
}
}
}
客户端实现:
//TODO
参考:
1.https://blog.csdn.net/Paddy90/article/details/71123196
2.https://www.cnblogs.com/mind-water/articles/10399995.html
有疑问加站长微信联系(非本文作者)