|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "flag" |
| 6 | + "log" |
| 7 | + "net" |
| 8 | + "net/http" |
| 9 | + _ "net/http/pprof" |
| 10 | + |
| 11 | + example "github.com/rpcxio/rpcx-examples" |
| 12 | + "github.com/smallnest/rpcx/client" |
| 13 | +) |
| 14 | + |
| 15 | +var ( |
| 16 | + addr = flag.String("addr", "localhost:8972", "server address") |
| 17 | +) |
| 18 | + |
| 19 | +var ( |
| 20 | + xclient client.XClient |
| 21 | +) |
| 22 | + |
| 23 | +func main() { |
| 24 | + flag.Parse() |
| 25 | + |
| 26 | + go http.ListenAndServe(":9099", nil) |
| 27 | + d, _ := client.NewPeer2PeerDiscovery("tcp@"+*addr, "") |
| 28 | + xclient = client.NewXClient("Arith", client.Failtry, client.RandomSelect, d, client.DefaultOption) |
| 29 | + defer xclient.Close() |
| 30 | + |
| 31 | + plugins := client.NewPluginContainer() |
| 32 | + plugins.Add(&ConnectionPlugin{}) |
| 33 | + xclient.SetPlugins(plugins) |
| 34 | + |
| 35 | + args := example.Args{ |
| 36 | + A: 10, |
| 37 | + B: 20, |
| 38 | + } |
| 39 | + |
| 40 | + reply := &example.Reply{} |
| 41 | + err := xclient.Call(context.Background(), "Mul", args, reply) |
| 42 | + if err != nil { |
| 43 | + log.Fatalf("failed to call: %v", err) |
| 44 | + } |
| 45 | + |
| 46 | + log.Printf("%d * %d = %d", args.A, args.B, reply.C) |
| 47 | + |
| 48 | +} |
| 49 | + |
| 50 | +type ConnectionPlugin struct { |
| 51 | +} |
| 52 | + |
| 53 | +func (p *ConnectionPlugin) ClientConnected(conn net.Conn) (net.Conn, error) { |
| 54 | + log.Printf("server %v connected", conn.RemoteAddr().String()) |
| 55 | + |
| 56 | + args := example.Args{ |
| 57 | + A: 10, |
| 58 | + B: 20, |
| 59 | + } |
| 60 | + |
| 61 | + reply := &example.Reply{} |
| 62 | + err := xclient.Call(context.Background(), "Mul", args, reply) |
| 63 | + if err != nil { |
| 64 | + log.Fatalf("failed to call: %v", err) |
| 65 | + } |
| 66 | + |
| 67 | + log.Printf("%d * %d = %d", args.A, args.B, reply.C) |
| 68 | + |
| 69 | + return conn, nil |
| 70 | +} |
| 71 | + |
| 72 | +func (p *ConnectionPlugin) ClientConnectionClose(conn net.Conn) error { |
| 73 | + log.Printf("server %v closed", conn.RemoteAddr().String()) |
| 74 | + return nil |
| 75 | +} |
0 commit comments