一、客户端代码如下:
package main
import (
"fmt"
"golang.org/x/net/context"
"google.golang.org/grpc"
api "grpc-test/src/test"
"log"
"sync"
"time"
)
type client struct {
receive api.DataClient
}
var c client = client{}
func main() {
var wg sync.WaitGroup
wg.Add(2)
go clientRequire()
time.Sleep(time.Second)
go cycleTest()
wg.Wait()
}
func clientRequire() {
timer := time.NewTicker(time.Millisecond * 100)
for {
select {
case <-timer.C:
conn, err := grpc.Dial("10.53.8.128:9999", grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
// 函数结束时关闭连接
defer conn.Close()
c.receive = api.NewDataClient(conn)
}
}
}
func cycleTest() {
timer := time.NewTicker(time.Millisecond * 100)
for {
select {
case <-timer.C:
c.order()
}
}
}
func (c *client) order() {
var set *api.ButtonSet
set = &api.ButtonSet{
ButtonName: "lastHole",
Value: true,
}
v, err := c.receive.SetHandleButton(context.Background(), set) //autoDrill,forceShock,pauseOrRun,lastHole
//time.Sleep(time.Second*10)
//v, err = c.receive.SetHandleButton(context.Background(), &api.ButtonSet{ButtonName:"pauseOrRun",Value: false})//autoDrill,forceShock,pauseOrRun
if err != nil {
fmt.Println("失败",time.Now())
//log.Fatalf("请求服务失败: %v", err)
}
if v == nil {
fmt.Println("v==nil")
} else {
fmt.Println("请求成功", v.Code,time.Now())
}
}
二、接口文件如下:
syntax = "proto3"; // 协议为proto3
package api; // 包名
option go_package = "/;api";
// 空消息
message Empty {};
// 简单返回结果
message ResultCode {
int32 code = 1;
}
//接收按键名字和bool命令
message ButtonSet{
string buttonName = 1;
bool value = 2;
}
//上传凿岩机控制信息
message SendRockOrder{
bool drillCompleted = 1;
double shockPressureSet = 2;
double pushPressureSet = 3;
int32 workStage = 4;
}
//底盘报警码
message AlarmSet{
int32 alarmCode = 1;
}
enum PushP{
LowPush = 0;
HighPush = 1;
}
message Push {
PushP pushOption=1;
}
// 定义服务,可定义多个服务,每个服务可多个接口
service Data {
//==============================================
rpc SetHandleButton(ButtonSet)returns(ResultCode);
//向下位机设置底盘报警信息
rpc SetChassisAlarm(AlarmSet)returns (ResultCode);
//上传下位机的控制命令
rpc GetRockOrder(Empty)returns(SendRockOrder);
//向下位机设置低推,高推
rpc SetPushPressure(Push)returns (ResultCode);
}
//protoc.exe --go_out=plugins=grpc:. api.proto
欢迎有新想法的小伙伴补充及讨论,共同进步ing