srpc/client.go

65 lines
1.0 KiB
Go
Raw Normal View History

2019-10-22 01:32:56 +02:00
package srpc
2020-02-10 02:53:05 +01:00
import (
"bytes"
"fmt"
"io"
"net"
)
2019-10-22 01:32:56 +02:00
var REQUEST_HEADER_SIZE = int32(8)
type requestHeader struct {
2020-02-10 02:53:05 +01:00
Size int64
}
type request struct {
FuncName string
Payload []byte
}
type Client struct {
ed IEncoderDecoder
conn net.Conn
}
2020-02-14 01:51:30 +01:00
func (client *Client) Call(funcName string, args ...interface{}) (ret []byte, ok bool) {
2020-02-10 02:53:05 +01:00
var b bytes.Buffer
2020-02-14 01:51:30 +01:00
ok = true
2020-02-10 02:53:05 +01:00
enc := client.ed.NewEncoder(&b)
for _, a := range args {
enc.Encode(a)
}
payload := b.Bytes()
req := request{funcName, payload}
fmt.Println(req)
enc = client.ed.NewEncoder(client.conn)
enc.Encode(req)
2020-02-14 01:51:30 +01:00
var header responseHeader
2020-02-10 02:53:05 +01:00
dec := client.ed.NewDecoder(client.conn)
2020-02-14 01:51:30 +01:00
dec.Decode(&header)
fmt.Println(header.Size)
fmt.Println(header.Status)
2020-02-10 02:53:05 +01:00
2020-02-14 01:51:30 +01:00
respData := make([]byte, header.Size)
2020-02-10 02:53:05 +01:00
dec.Decode(&respData)
2020-02-14 01:51:30 +01:00
if header.Status != OK {
ok = false
}
return respData, ok
2020-02-10 02:53:05 +01:00
}
func (client *Client) NewDecoder(r io.Reader) IDecoder {
return client.ed.NewDecoder(r)
}
func NewClient(conn net.Conn) *Client {
return &Client{NewEncoderDecoder(), conn}
2019-10-22 01:32:56 +02:00
}