/
gobClientCodec.go
51 lines (44 loc) · 1.12 KB
/
gobClientCodec.go
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
package rpcsv
import (
"bufio"
"encoding/gob"
"github.com/toukii/goutils"
"io"
"net"
"net/rpc"
"time"
)
type RPCgobClientCodec struct {
rwc io.ReadWriteCloser
dec *gob.Decoder
enc *gob.Encoder
encBuf *bufio.Writer
}
func (c *RPCgobClientCodec) WriteRequest(r *rpc.Request, body interface{}) (err error) {
if err = TimeoutCoder(c.enc.Encode, r, "client write request"); err != nil {
return
}
if err = TimeoutCoder(c.enc.Encode, body, "client write request body"); err != nil {
return
}
return c.encBuf.Flush()
}
func (c *RPCgobClientCodec) ReadResponseHeader(r *rpc.Response) error {
return c.dec.Decode(r)
}
func (c *RPCgobClientCodec) ReadResponseBody(body interface{}) error {
return c.dec.Decode(body)
}
func (c *RPCgobClientCodec) Close() error {
return c.rwc.Close()
}
func RPCClientWithCodec(tcp_addr string) *rpc.Client {
conn, err := net.DialTimeout("tcp", tcp_addr, time.Second*5)
if goutils.CheckErr(err) {
return nil
}
encBuf := bufio.NewWriter(conn)
codec := &RPCgobClientCodec{conn, gob.NewDecoder(conn), gob.NewEncoder(encBuf), encBuf}
c := rpc.NewClientWithCodec(codec)
return c
}