dispatcher_test.go 1.9 KB

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