protocol.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package protocol
  2. import (
  3. "encoding/binary"
  4. "io"
  5. "net"
  6. )
  7. type Client interface {
  8. Close() error
  9. }
  10. // Protocol describes the basic behavior of any protocol in the system
  11. type Protocol interface {
  12. NewClient(net.Conn) Client
  13. IOLoop(Client) error
  14. }
  15. // SendResponse is a server side utility function to prefix data with a length header
  16. // and write to the supplied Writer
  17. func SendResponse(w io.Writer, data []byte) (int, error) {
  18. err := binary.Write(w, binary.BigEndian, int32(len(data)))
  19. if err != nil {
  20. return 0, err
  21. }
  22. n, err := w.Write(data)
  23. if err != nil {
  24. return 0, err
  25. }
  26. return (n + 4), nil
  27. }
  28. // SendFramedResponse is a server side utility function to prefix data with a length header
  29. // and frame header and write to the supplied Writer
  30. func SendFramedResponse(w io.Writer, frameType int32, data []byte) (int, error) {
  31. beBuf := make([]byte, 4)
  32. size := uint32(len(data)) + 4
  33. binary.BigEndian.PutUint32(beBuf, size)
  34. n, err := w.Write(beBuf)
  35. if err != nil {
  36. return n, err
  37. }
  38. binary.BigEndian.PutUint32(beBuf, uint32(frameType))
  39. n, err = w.Write(beBuf)
  40. if err != nil {
  41. return n + 4, err
  42. }
  43. n, err = w.Write(data)
  44. return n + 8, err
  45. }