dispatcher_test.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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/transport/internet/udp"
  10. "v2ray.com/core/transport/ray"
  11. . "v2ray.com/ext/assert"
  12. )
  13. type TestDispatcher struct {
  14. OnDispatch func(ctx context.Context, dest net.Destination) (ray.InboundRay, error)
  15. }
  16. func (d *TestDispatcher) Dispatch(ctx context.Context, dest net.Destination) (ray.InboundRay, error) {
  17. return d.OnDispatch(ctx, dest)
  18. }
  19. func (d *TestDispatcher) Start() error {
  20. return nil
  21. }
  22. func (d *TestDispatcher) Close() {}
  23. func TestSameDestinationDispatching(t *testing.T) {
  24. assert := With(t)
  25. ctx, cancel := context.WithCancel(context.Background())
  26. link := ray.NewRay(ctx)
  27. go func() {
  28. for {
  29. data, err := link.OutboundInput().ReadMultiBuffer()
  30. if err != nil {
  31. break
  32. }
  33. err = link.OutboundOutput().WriteMultiBuffer(data)
  34. assert(err, IsNil)
  35. }
  36. }()
  37. var count uint32
  38. td := &TestDispatcher{
  39. OnDispatch: func(ctx context.Context, dest net.Destination) (ray.InboundRay, error) {
  40. atomic.AddUint32(&count, 1)
  41. return link, nil
  42. },
  43. }
  44. dest := net.UDPDestination(net.LocalHostIP, 53)
  45. b := buf.New()
  46. b.AppendBytes('a', 'b', 'c', 'd')
  47. dispatcher := NewDispatcher(td)
  48. var msgCount uint32
  49. dispatcher.Dispatch(ctx, dest, b, func(payload *buf.Buffer) {
  50. atomic.AddUint32(&msgCount, 1)
  51. })
  52. for i := 0; i < 5; i++ {
  53. dispatcher.Dispatch(ctx, dest, b, func(payload *buf.Buffer) {})
  54. }
  55. time.Sleep(time.Second)
  56. cancel()
  57. assert(count, Equals, uint32(1))
  58. assert(msgCount, Equals, uint32(6))
  59. }