dispatcher_test.go 1.9 KB

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