conn.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. WriteAuthInfo(channel string, auth []byte) (err error)
  28. ReadAuthInfo() (proto string, version uint8, channel string, auth []byte, err error)
  29. WriteRequest(id uint16, cmd string, data []byte) error
  30. WriteResponse(id uint16, state uint8, data []byte) error
  31. WritePing(id uint16) error
  32. ReadMessage(deadline int) (msgType MsgType, id uint16, cmd string, state uint8, data []byte, err error)
  33. RemoteIP() net.IP
  34. LocalIP() net.IP
  35. Close() error
  36. }
  37. // 服务请求连接
  38. type ServerConnectFunc func(conn Connect)
  39. // addrToIP attempts to extract a net.IP from a net.Addr
  40. func AddrToIP(addr net.Addr) net.IP {
  41. switch v := addr.(type) {
  42. case *net.TCPAddr:
  43. return v.IP
  44. case *net.UDPAddr:
  45. return v.IP
  46. case *net.IPAddr:
  47. return v.IP
  48. default:
  49. // Handle other potential net.Addr implementations or return nil
  50. return nil
  51. }
  52. }