type.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package conn
  2. import (
  3. "fmt"
  4. "net"
  5. )
  6. // 消息类型
  7. type MsgType byte
  8. const (
  9. PingMsg MsgType = iota
  10. RequestMsg
  11. ResponseMsg
  12. )
  13. func (t MsgType) String() string {
  14. switch t {
  15. case PingMsg:
  16. return "PingMsg"
  17. case RequestMsg:
  18. return "RequestMsg"
  19. case ResponseMsg:
  20. return "ResponseMsg"
  21. default:
  22. return fmt.Sprintf("Unknown MsgType (%d)", t)
  23. }
  24. }
  25. // 连接接口,代表一个原始的连接
  26. type Connect interface {
  27. // io.ReadWriteCloser
  28. WriteAuthInfo(channel string, auth []byte) (err error)
  29. ReadAuthInfo() (proto string, version uint8, channel string, auth []byte, err error)
  30. WriteRequest(id uint16, cmd string, data []byte) error
  31. WriteResponse(id uint16, state uint8, data []byte) error
  32. WritePing(id uint16) error
  33. ReadMessage(deadline int) (msgType MsgType, id uint16, cmd string, state uint8, data []byte, err error)
  34. RemoteIP() net.IP
  35. LocalIP() net.IP
  36. Close() error
  37. }
  38. // 服务请求连接
  39. type ServerConnectFunc func(conn Connect)
  40. // addrToIP attempts to extract a net.IP from a net.Addr
  41. func AddrToIP(addr net.Addr) net.IP {
  42. switch v := addr.(type) {
  43. case *net.TCPAddr:
  44. return v.IP
  45. case *net.UDPAddr:
  46. return v.IP
  47. case *net.IPAddr:
  48. return v.IP
  49. default:
  50. // Handle other potential net.Addr implementations or return nil
  51. return nil
  52. }
  53. }