dial-pool.go 655 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package torrent
  2. import (
  3. "context"
  4. )
  5. type dialPool struct {
  6. resCh chan DialResult
  7. addr string
  8. left int
  9. }
  10. func (me *dialPool) getFirst() (res DialResult) {
  11. for me.left > 0 && res.Conn == nil {
  12. res = <-me.resCh
  13. me.left--
  14. }
  15. return
  16. }
  17. func (me *dialPool) add(ctx context.Context, dialer Dialer) {
  18. me.left++
  19. go func() {
  20. me.resCh <- DialResult{
  21. dialFromSocket(ctx, dialer, me.addr),
  22. dialer,
  23. }
  24. }()
  25. }
  26. func (me *dialPool) startDrainer() {
  27. go me.drainAndCloseRemainingDials()
  28. }
  29. func (me *dialPool) drainAndCloseRemainingDials() {
  30. for me.left > 0 {
  31. conn := (<-me.resCh).Conn
  32. me.left--
  33. if conn != nil {
  34. conn.Close()
  35. }
  36. }
  37. }