slimming/rpc_client.go

124 lines
2.0 KiB
Go
Raw Normal View History

2022-08-31 09:52:16 +00:00
package main
import (
"bytes"
"context"
"log"
gen "slimming/proto/gen"
"sync"
2022-09-01 06:59:30 +00:00
"time"
2022-08-31 09:52:16 +00:00
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type RPCClient struct {
2022-09-01 06:59:30 +00:00
Frames [][]byte
2022-08-31 09:52:16 +00:00
realAddr string
conn *grpc.ClientConn
lock sync.Mutex
2022-09-01 06:59:30 +00:00
trigger chan bool
2022-08-31 09:52:16 +00:00
}
func NewRPCClient(realAddr string) *RPCClient {
return &RPCClient{
realAddr: realAddr,
2022-09-01 06:59:30 +00:00
Frames: make([][]byte, 0, 1000),
conn: nil,
lock: sync.Mutex{},
trigger: make(chan bool),
2022-08-31 09:52:16 +00:00
}
}
func (cli *RPCClient) Lock(do func() bool) bool {
cli.lock.Lock()
defer cli.lock.Unlock()
return do()
}
func (cli *RPCClient) CheckConnect() {
if cli.Lock(func() bool {
return cli.conn != nil
}) {
return
}
log.Println("rpcclient connect", cli.realAddr)
// defer log.Println("rpcclient exit")
conn, err := grpc.Dial(cli.realAddr,
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
log.Printf("did not connect: %v", err)
return
}
cli.conn = conn
go cli.run()
}
2022-09-01 06:59:30 +00:00
func (cli *RPCClient) Push(frame []byte) {
cli.lock.Lock()
defer cli.lock.Unlock()
cli.Frames = append(cli.Frames, frame)
if len(cli.Frames) >= 1000 {
cli.trigger <- true
}
}
2022-08-31 09:52:16 +00:00
func (cli *RPCClient) run() {
defer log.Println("rpcclient exit")
defer func() {
if err := recover(); err != nil {
log.Println("recover", err)
cli.Lock(func() bool {
err = cli.conn.Close()
if err != nil {
log.Println(err)
}
cli.conn = nil
return false
})
}
}()
cliService := gen.NewFrameServiceClient(cli.conn)
stream, err := cliService.SendFrames(context.Background())
if err != nil {
log.Panic(err)
}
defer stream.CloseSend()
2022-09-01 06:59:30 +00:00
var ticker = time.NewTicker(time.Millisecond * 20)
2022-08-31 09:52:16 +00:00
var frames [][]byte
buf := bytes.NewBuffer(nil)
2022-09-01 06:59:30 +00:00
for {
select {
case <-cli.trigger:
case <-ticker.C:
}
2022-09-01 06:42:12 +00:00
buf.Reset()
2022-09-01 06:59:30 +00:00
cli.Lock(func() bool {
Compress(buf, frames)
2022-09-01 07:01:06 +00:00
frames = frames[:0]
2022-09-01 06:59:30 +00:00
return true
})
2022-08-31 09:52:16 +00:00
2022-09-01 06:42:12 +00:00
// 发到对面的网卡
err = stream.Send(&gen.RequestFrames{
Frames: buf.Bytes(),
})
2022-08-31 09:52:16 +00:00
2022-09-01 06:42:12 +00:00
if err != nil {
log.Panic(err)
2022-08-31 09:52:16 +00:00
}
}
}