2019-10-22 01:32:56 +02:00
|
|
|
package srpc
|
|
|
|
|
2020-02-10 02:53:05 +01:00
|
|
|
import (
|
|
|
|
"bytes"
|
2020-02-14 19:55:35 +01:00
|
|
|
"errors"
|
2020-02-10 02:53:05 +01:00
|
|
|
"io"
|
|
|
|
"net"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Client struct {
|
|
|
|
ed IEncoderDecoder
|
2020-02-14 19:55:35 +01:00
|
|
|
conn IRPCConn
|
2020-02-10 02:53:05 +01:00
|
|
|
}
|
|
|
|
|
2020-02-14 19:55:35 +01:00
|
|
|
func (client *Client) Call(funcName string, args ...interface{}) (ret []byte, err error) {
|
|
|
|
defer client.conn.Close()
|
|
|
|
|
2020-02-10 02:53:05 +01:00
|
|
|
var b bytes.Buffer
|
|
|
|
|
|
|
|
enc := client.ed.NewEncoder(&b)
|
|
|
|
for _, a := range args {
|
|
|
|
enc.Encode(a)
|
|
|
|
}
|
|
|
|
|
|
|
|
payload := b.Bytes()
|
2020-02-14 19:55:35 +01:00
|
|
|
req := RPCRequest{funcName, payload}
|
2020-02-10 02:53:05 +01:00
|
|
|
|
2020-02-14 19:55:35 +01:00
|
|
|
if err = client.conn.SendRequest(&req); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-02-10 02:53:05 +01:00
|
|
|
|
2020-02-14 19:55:35 +01:00
|
|
|
var response *RPCResponse
|
|
|
|
if response, err = client.conn.ReceiveResponse(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-02-10 02:53:05 +01:00
|
|
|
|
2020-02-14 19:55:35 +01:00
|
|
|
if response.Status != RPCOK {
|
|
|
|
err = errors.New("srpc - Response contained error: '" + response.Error + "'")
|
2020-02-14 01:51:30 +01:00
|
|
|
}
|
|
|
|
|
2020-02-14 19:55:35 +01:00
|
|
|
return response.Payload, err
|
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 {
|
2020-02-14 19:55:35 +01:00
|
|
|
return &Client{NewEncoderDecoder(), NewTCPConn(conn, NewEncoderDecoder())}
|
2019-10-22 01:32:56 +02:00
|
|
|
}
|