dispatcher_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package udp_test
  2. import (
  3. "context"
  4. "sync/atomic"
  5. "testing"
  6. "time"
  7. "v2ray.com/core"
  8. "v2ray.com/core/common/buf"
  9. "v2ray.com/core/common/net"
  10. . "v2ray.com/core/transport/internet/udp"
  11. "v2ray.com/core/transport/pipe"
  12. . "v2ray.com/ext/assert"
  13. )
  14. type TestDispatcher struct {
  15. OnDispatch func(ctx context.Context, dest net.Destination) (*core.Link, error)
  16. }
  17. func (d *TestDispatcher) Dispatch(ctx context.Context, dest net.Destination) (*core.Link, error) {
  18. return d.OnDispatch(ctx, dest)
  19. }
  20. func (d *TestDispatcher) Start() error {
  21. return nil
  22. }
  23. func (d *TestDispatcher) Close() error {
  24. return nil
  25. }
  26. func TestSameDestinationDispatching(t *testing.T) {
  27. assert := With(t)
  28. ctx, cancel := context.WithCancel(context.Background())
  29. uplinkReader, uplinkWriter := pipe.New(pipe.WithSizeLimit(1024))
  30. downlinkReader, downlinkWriter := pipe.New(pipe.WithSizeLimit(1024))
  31. go func() {
  32. for {
  33. data, err := uplinkReader.ReadMultiBuffer()
  34. if err != nil {
  35. break
  36. }
  37. err = downlinkWriter.WriteMultiBuffer(data)
  38. assert(err, IsNil)
  39. }
  40. }()
  41. var count uint32
  42. td := &TestDispatcher{
  43. OnDispatch: func(ctx context.Context, dest net.Destination) (*core.Link, error) {
  44. atomic.AddUint32(&count, 1)
  45. return &core.Link{Reader: downlinkReader, Writer: uplinkWriter}, nil
  46. },
  47. }
  48. dest := net.UDPDestination(net.LocalHostIP, 53)
  49. b := buf.New()
  50. b.WriteBytes('a', 'b', 'c', 'd')
  51. var msgCount uint32
  52. dispatcher := NewDispatcher(td, func(ctx context.Context, payload *buf.Buffer) {
  53. atomic.AddUint32(&msgCount, 1)
  54. })
  55. dispatcher.Dispatch(ctx, dest, b)
  56. for i := 0; i < 5; i++ {
  57. dispatcher.Dispatch(ctx, dest, b)
  58. }
  59. time.Sleep(time.Second)
  60. cancel()
  61. assert(count, Equals, uint32(1))
  62. assert(atomic.LoadUint32(&msgCount), Equals, uint32(6))
  63. }