49 lines
716 B
Go
49 lines
716 B
Go
package rpc
|
|
|
|
import (
|
|
"encoding/binary"
|
|
"io"
|
|
"net"
|
|
)
|
|
|
|
func TCPWriteData(conn net.Conn, buf []byte) error {
|
|
var wErr error
|
|
|
|
prefix := make([]byte, 4)
|
|
binary.BigEndian.PutUint32(prefix, uint32(len(buf)))
|
|
|
|
_, wErr = conn.Write(prefix)
|
|
if nil != wErr {
|
|
return wErr
|
|
}
|
|
_, wErr = conn.Write(buf)
|
|
if nil != wErr {
|
|
return wErr
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func TCPReadData(conn net.Conn) ([]byte, error) {
|
|
var (
|
|
buf []byte
|
|
rErr error
|
|
)
|
|
|
|
prefix := make([]byte, 4)
|
|
_, rErr = io.ReadFull(conn, prefix)
|
|
if nil != rErr {
|
|
return nil, rErr
|
|
}
|
|
|
|
length := binary.BigEndian.Uint32(prefix)
|
|
|
|
buf = make([]byte, int(length))
|
|
_, rErr = io.ReadFull(conn, buf)
|
|
if nil != rErr {
|
|
return nil, rErr
|
|
}
|
|
|
|
return buf, nil
|
|
}
|