portmanager.go 768 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package gb28181
  2. import "io"
  3. type PortManager struct {
  4. recycle chan uint16
  5. max uint16
  6. pos uint16
  7. Valid bool
  8. }
  9. func (pm *PortManager) Init(start, end uint16) {
  10. pm.pos = start - 1
  11. pm.max = end
  12. if pm.pos > 0 && pm.max > pm.pos {
  13. pm.Valid = true
  14. pm.recycle = make(chan uint16, pm.Range())
  15. }
  16. }
  17. func (pm *PortManager) Range() uint16 {
  18. return pm.max - pm.pos
  19. }
  20. func (pm *PortManager) Recycle(p uint16) (err error) {
  21. select {
  22. case pm.recycle <- p:
  23. return nil
  24. default:
  25. return io.EOF //TODO: 换一个Error
  26. }
  27. }
  28. func (pm *PortManager) GetPort() (p uint16, err error) {
  29. select {
  30. case p = <-pm.recycle:
  31. return
  32. default:
  33. if pm.Range() > 0 {
  34. pm.pos++
  35. p = pm.pos
  36. return
  37. } else {
  38. return 0, io.EOF //TODO: 换一个Error
  39. }
  40. }
  41. }