github.com/matrixorigin/matrixone@v1.2.0/pkg/common/morpc/examples/pingpong/main.go (about) 1 // Copyright 2021 - 2022 Matrix Origin 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package main 16 17 import ( 18 "context" 19 "os" 20 "time" 21 22 "github.com/matrixorigin/matrixone/pkg/common/morpc" 23 "github.com/matrixorigin/matrixone/pkg/common/morpc/examples/message" 24 "github.com/matrixorigin/matrixone/pkg/logutil" 25 ) 26 27 var ( 28 addr = "unix:///tmp/pingpong.sock" 29 file = "/tmp/pingpong.sock" 30 ) 31 32 func main() { 33 if err := os.RemoveAll(file); err != nil { 34 panic(err) 35 } 36 37 if err := startServer(); err != nil { 38 panic(err) 39 } 40 41 bf := morpc.NewGoettyBasedBackendFactory(newCodec()) 42 cli, err := morpc.NewClient("example-rpc", bf, morpc.WithClientMaxBackendPerHost(1)) 43 if err != nil { 44 panic(err) 45 } 46 47 ctx, cancel := context.WithTimeout(context.Background(), time.Second) 48 defer cancel() 49 50 f, err := cli.Send(ctx, addr, &message.ExampleMessage{MsgID: 1, Content: "hello"}) 51 if err != nil { 52 panic(err) 53 } 54 defer f.Close() 55 56 resp, err := f.Get() 57 if err != nil { 58 panic(err) 59 } 60 61 logutil.Infof("%s", resp.DebugString()) 62 } 63 64 func startServer() error { 65 s, err := morpc.NewRPCServer("test-unix-server", addr, newCodec()) 66 if err != nil { 67 return err 68 } 69 s.RegisterRequestHandler(func(ctx context.Context, request morpc.RPCMessage, sequence uint64, cs morpc.ClientSession) error { 70 // write request back to client 71 return cs.Write(ctx, request.Message) 72 }) 73 74 return s.Start() 75 } 76 77 func newCodec() morpc.Codec { 78 return morpc.NewMessageCodec(func() morpc.Message { return &message.ExampleMessage{} }) 79 }