slimming/rpc.go

91 lines
1.7 KiB
Go
Raw Normal View History

2022-08-23 09:58:07 +00:00
package slimming
import (
"context"
"flag"
"fmt"
"log"
"net"
gen "slimming/proto/gen"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type RPCServer struct {
gen.UnimplementedFrameServiceServer
FrameChan chan [][]byte
}
var (
serverPort = flag.Int("port", 50051, "The server port")
othersAddr = flag.String("addr", "", "The other server addr")
)
var rpcServer = func() *RPCServer {
rs := &RPCServer{}
conn, err := grpc.Dial(*othersAddr,
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := gen.NewFrameServiceClient(conn)
// Contact the server and print out its response.
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
stream, err := c.SendFrames(ctx)
if err != nil {
panic(err)
}
err = stream.Send(&gen.Request{
Frames: <-rs.FrameChan,
})
if err != nil {
panic(err)
}
return rs
}()
func (rpc *RPCServer) Run() {
flag.Parse()
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *serverPort))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
gen.RegisterFrameServiceServer(s, rpc)
log.Printf("server listening at %v", lis.Addr())
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
// SayHello implements helloworld.GreeterServer
func (s *RPCServer) SendFrames(stream gen.FrameService_SendFramesServer) error {
log.Printf("Received: %v", stream)
for {
request, err := stream.Recv()
if err != nil {
log.Panic(err)
}
netCard.FrameChan <- request.GetFrames()
}
// err := stream.SendAndClose(&gen.Response{Code: 0})
// if err != nil {
// log.Panic(err)
// }
return nil
}