rpc.go 726 B

1234567891011121314151617181920212223242526272829303132333435
  1. package rpc
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/binary"
  6. "errors"
  7. "io"
  8. )
  9. func WriteBytes(w io.Writer, buf []byte) (int, error) {
  10. out := bytes.NewBuffer(nil)
  11. binary.Write(out, binary.BigEndian, int64(len(buf)))
  12. out.Write(buf)
  13. return w.Write(out.Bytes())
  14. }
  15. func ReadBytes(r io.Reader) ([]byte, error) {
  16. // To compatible with UDP connection, use bufio reader here to avoid lost conent.
  17. rd := bufio.NewReader(r)
  18. var length int64
  19. if err := binary.Read(rd, binary.BigEndian, &length); err != nil {
  20. return nil, err
  21. }
  22. buffer := make([]byte, length)
  23. n, err := io.ReadFull(rd, buffer)
  24. if err != nil {
  25. return nil, err
  26. }
  27. if int64(n) != length {
  28. return nil, errors.New("invalid length")
  29. }
  30. return buffer, nil
  31. }