1+ package impl
2+
3+ import (
4+ "fmt"
5+ "github.com/golang/glog"
6+ "net"
7+ "net/rpc"
8+ "net/rpc/jsonrpc"
9+ "os"
10+ )
11+
12+ // RPC数据结构
13+ type RPCSt struct {
14+ ServiceUrl string
15+ SendData interface {} // 发送的数据
16+ ReplyData interface {} // 接受的数据
17+ ConnRPC * rpc.Client
18+ }
19+
20+ func NewClientConnRPC (Addr string ) * RPCSt {
21+ return & RPCSt {
22+ ServiceUrl :Addr ,
23+ SendData :nil ,
24+ ReplyData :nil ,
25+ ConnRPC :createClientConn (Addr ),
26+ }
27+ }
28+
29+ func createClientConn (Addr string ) * rpc.Client {
30+ client , err := jsonrpc .Dial ("tcp" , Addr )
31+ if err != nil {
32+ glog .Info ("dial error:" , err )
33+ return nil
34+ }
35+ return client
36+ }
37+
38+ func (this * RPCSt )GetClientConnRPC () * rpc.Client {
39+ if this .ConnRPC != nil {
40+ return this .ConnRPC
41+ }else {
42+ client , err := jsonrpc .Dial ("tcp" , this .ServiceUrl )
43+ if err != nil {
44+ glog .Info ("dial error:" , err )
45+ return nil
46+ }
47+ return client
48+ }
49+ }
50+
51+ // 实际操作信息,
52+ func (this * RPCSt )Send_LollipopGoRPC (data RPCSt ) interface {} {
53+ if this .ConnRPC == nil {
54+ return nil
55+ }
56+ args := data
57+ var reply RPCSt
58+ divCall := this .ConnRPC .Go ("RPCSt.LollipopGoRPC" , args , & reply , nil )
59+ replyCall := <- divCall .Done
60+ glog .Info (replyCall .Reply )
61+ glog .Info ("the arith.LollipopGoRPC is :" , reply )
62+ return reply
63+ }
64+
65+ //----------------------------------------------------------------------------------------------------------------------
66+ // RPC 服务器调用
67+
68+ func MainListener (strport string ) {
69+ rpcRegister ()
70+ tcpAddr , err := net .ResolveTCPAddr ("tcp" , ":" + strport )
71+ checkError (err )
72+ Listener , err := net .ListenTCP ("tcp" , tcpAddr )
73+ checkError (err )
74+ for {
75+ defer func () {
76+ if err := recover (); err != nil {
77+ strerr := fmt .Sprintf ("%s" , err )
78+ fmt .Println ("异常捕获:" , strerr )
79+ }
80+ }()
81+ conn , err := Listener .Accept ()
82+ if err != nil {
83+ fmt .Fprint (os .Stderr , "accept err: %s" , err .Error ())
84+ continue
85+ }
86+ go jsonrpc .ServeConn (conn )
87+ }
88+ }
89+
90+ func rpcRegister () {
91+ _ = rpc .Register (new (RPCSt ))
92+ }
93+
94+ func checkError (err error ) {
95+ if err != nil {
96+ fmt .Fprint (os .Stderr , "Usage: %s" , err .Error ())
97+ }
98+ }
0 commit comments