srpc/connection.go

147 lines
2.4 KiB
Go
Raw Normal View History

package srpc
import (
2020-02-17 01:30:24 +01:00
"io"
"net"
2020-02-17 01:30:24 +01:00
"sync"
)
type RPCStatus uint8
const (
RPCOK RPCStatus = 0
RPCERR RPCStatus = 1
)
type RPCRequest struct {
FuncName string
Payload []byte
}
type RPCResponse struct {
Status RPCStatus
Error string
Payload []byte
}
type IRPCConn interface {
ReceiveRequest() (*RPCRequest, error)
ReceiveResponse() (*RPCResponse, error)
SendRequest(request *RPCRequest) error
SendResponse(response *RPCResponse) error
Close()
}
type TCPConn struct {
conn net.Conn
ed IEncoderDecoder
// interface
IRPCConn
}
func (tc *TCPConn) ReceiveRequest() (ret *RPCRequest, err error) {
ret = new(RPCRequest)
dec := tc.ed.NewDecoder(tc.conn)
if err = dec.Decode(ret); err != nil {
return nil, err
}
return ret, err
}
func (tc *TCPConn) ReceiveResponse() (ret *RPCResponse, err error) {
ret = new(RPCResponse)
dec := tc.ed.NewDecoder(tc.conn)
if err = dec.Decode(ret); err != nil {
return nil, err
}
return ret, err
}
func (tc *TCPConn) SendRequest(request *RPCRequest) (err error) {
enc := tc.ed.NewEncoder(tc.conn)
err = enc.Encode(request)
return err
}
func (tc *TCPConn) SendResponse(response *RPCResponse) (err error) {
enc := tc.ed.NewEncoder(tc.conn)
err = enc.Encode(response)
return err
}
func (tc *TCPConn) Close() {
tc.conn.Close()
}
func NewTCPConn(conn net.Conn, ed IEncoderDecoder) *TCPConn {
ret := &TCPConn{}
ret.conn = conn
ret.ed = ed
return ret
}
2020-02-17 01:30:24 +01:00
type NetHeartbeatConn struct {
sync.Mutex
conn io.ReadWriteCloser
dec IDecoder
enc IEncoder
// interfaces
IRPCConn
}
func (nhc *NetHeartbeatConn) ReceiveRequest() (ret *RPCRequest, err error) {
nhc.Lock()
defer nhc.Unlock()
ret = new(RPCRequest)
if err = nhc.dec.Decode(ret); err != nil {
return nil, err
}
return ret, err
}
func (nhc *NetHeartbeatConn) ReceiveResponse() (ret *RPCResponse, err error) {
nhc.Lock()
defer nhc.Unlock()
ret = new(RPCResponse)
if err = nhc.dec.Decode(ret); err != nil {
return nil, err
}
return ret, err
}
func (nhc *NetHeartbeatConn) SendRequest(request *RPCRequest) (err error) {
nhc.Lock()
defer nhc.Unlock()
err = nhc.enc.Encode(request)
return err
}
func (nhc *NetHeartbeatConn) SendResponse(response *RPCResponse) (err error) {
nhc.Lock()
defer nhc.Unlock()
err = nhc.enc.Encode(response)
return err
}
func (nhc *NetHeartbeatConn) Close() {
nhc.Lock()
defer nhc.Unlock()
nhc.conn.Close()
}