1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
const RpcServiceName = "zrpc/rpcs.RpcService"
type RpcInterface interface {
RpcServiceFunc(request string, replay *string) error
}
func RegisterRpcSvr(svrName string, svc RpcInterface) error {
return rpc.RegisterName(svrName, svc)
}
// ----------- service 重构 ---------------
type RpcService struct{}
func (s *RpcService) RpcServiceFunc(request string, replay *string) error {
*replay = "service_func:" + request
return nil
}
func (s *RpcService) RpcServiceName() string {
return RpcServiceName
}
func RunService() {
rpcSvr := new(RpcService)
_ = RegisterRpcSvr(rpcSvr.RpcServiceName(), rpcSvr)
listener, err := net.Listen("tcp", addr)
if err != nil {
log.Fatal("ListenTCP error:", err)
}
for {
conn, err := listener.Accept()
if err != nil {
log.Fatal("Accept error:", err)
}
go rpc.ServeConn(conn)
}
}
// ---------- client 重构 ------------------
type RpcClient struct {
*rpc.Client
}
var _ RpcInterface = (*RpcClient)(nil)
func (c *RpcClient) RpcServiceFunc(request string, replay *string) error {
return c.Client.Call(RpcServiceName+".RpcServiceFunc", request, replay)
}
func DialRpcClient(network, address string) (*RpcClient, error) {
client, err := rpc.Dial(network, address)
if err != nil {
return nil, err
}
return &RpcClient{client}, nil
}
func RunClient() {
client, err := DialRpcClient("tcp", addr)
if err != nil {
log.Fatal("dialing:", err)
}
var reply string
err = client.RpcServiceFunc("hello rpc", &reply)
if err != nil {
log.Fatal(err)
}
fmt.Println(reply)
}
|