Skip to content

Instantly share code, notes, and snippets.

@jiphex
Created April 30, 2019 17:04
Show Gist options
  • Save jiphex/3224e007f4299f9c88d66c773f99a5a0 to your computer and use it in GitHub Desktop.
Save jiphex/3224e007f4299f9c88d66c773f99a5a0 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"net"
"os"
"time"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc"
"gitlab.dafni.rl.ac.uk/dafni/tools/rpctest/pkg/rpctest"
)
func main() {
var m string
var isset bool
if m, isset = os.LookupEnv("MODE"); !isset {
log.Fatal("need to set env var $MODE to either client or server")
}
switch m {
case "server":
lis, err := net.Listen("unix", "rpctest.sock")
if err != nil {
log.WithError(err).Fatal("bad listen")
}
grpcServer := grpc.NewServer()
s := &rpctest.RPCTestServer{}
rpctest.RegisterRpcTestServer(grpcServer, s)
grpcServer.Serve(lis)
case "client":
conn, err := grpc.Dial("unix:./rpctest.sock", grpc.WithInsecure())
if err != nil {
log.WithError(err).Fatal("cant dial server")
}
cl, err := rpctest.NewRpcTestClient(conn).ReportStatus(context.Background())
if err != nil {
log.WithError(err).Fatal("cant create rpc rs client")
}
i := 5
for i > 0 {
log.Printf("sending %d", i)
err := cl.Send(&rpctest.StatusReport{
Status: fmt.Sprintf("my number is %d", i),
})
if err != nil {
log.WithError(err).Fatal("bad send")
}
i--
time.Sleep(1 * time.Second)
}
repl, err := cl.CloseAndRecv()
if err != nil {
log.WithError(err).Error("bad reply")
}
log.Printf("got reply: %+v", repl)
}
}
syntax = "proto3";
service RpcTest {
rpc ReportStatus(stream StatusReport) returns (StatusReply) {}
}
message StatusReport {
string status = 1;
}
message StatusReply {
string reply = 1;
}
package rpctest
import (
"io"
log "github.com/sirupsen/logrus"
)
type RPCTestServer struct {
}
func (r *RPCTestServer) ReportStatus(stream RpcTest_ReportStatusServer) error {
for {
rep, err := stream.Recv()
if err == io.EOF {
log.Printf("Got the last message")
return stream.SendAndClose(&StatusReply{
Reply: "thanks",
})
} else if err != nil {
return err
}
log.Printf("got message: %+v", rep)
}
}
@jiphex
Copy link
Author

jiphex commented Apr 30, 2019

vpn-3-104% tree
.
├── Makefile
├── cmd
│   └── rpctest
│       └── main.go
├── go.mod
├── go.sum
├── pkg
│   └── rpctest
│       ├── rpctest.pb.go
│       ├── rpctest.proto
│       └── server.go
├── rpctest
└── rpctest.sock

4 directories, 9 files

@jiphex
Copy link
Author

jiphex commented Apr 30, 2019

vpn-3-104% protoc pkg/rpctest/rpctest.proto --go_out=plugins=grpc:.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment