kcp_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package kcp_test
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "io"
  6. "net"
  7. "sync"
  8. "testing"
  9. "time"
  10. v2net "v2ray.com/core/common/net"
  11. "v2ray.com/core/testing/assert"
  12. "v2ray.com/core/transport/internet"
  13. . "v2ray.com/core/transport/internet/kcp"
  14. )
  15. func TestDialAndListen(t *testing.T) {
  16. assert := assert.On(t)
  17. conns := make(chan internet.Connection, 16)
  18. listerner, err := NewListener(internet.ContextWithTransportSettings(context.Background(), &Config{}), v2net.LocalHostIP, v2net.Port(0), conns)
  19. assert.Error(err).IsNil()
  20. port := v2net.Port(listerner.Addr().(*net.UDPAddr).Port)
  21. go func() {
  22. for conn := range conns {
  23. go func(c internet.Connection) {
  24. payload := make([]byte, 4096)
  25. for {
  26. nBytes, err := c.Read(payload)
  27. if err != nil {
  28. break
  29. }
  30. for idx, b := range payload[:nBytes] {
  31. payload[idx] = b ^ 'c'
  32. }
  33. c.Write(payload[:nBytes])
  34. }
  35. c.Close()
  36. }(conn)
  37. }
  38. }()
  39. ctx := internet.ContextWithTransportSettings(context.Background(), &Config{})
  40. wg := new(sync.WaitGroup)
  41. for i := 0; i < 10; i++ {
  42. clientConn, err := DialKCP(ctx, v2net.UDPDestination(v2net.LocalHostIP, port))
  43. assert.Error(err).IsNil()
  44. wg.Add(1)
  45. go func() {
  46. clientSend := make([]byte, 1024*1024)
  47. rand.Read(clientSend)
  48. go clientConn.Write(clientSend)
  49. clientReceived := make([]byte, 1024*1024)
  50. nBytes, _ := io.ReadFull(clientConn, clientReceived)
  51. assert.Int(nBytes).Equals(len(clientReceived))
  52. clientConn.Close()
  53. clientExpected := make([]byte, 1024*1024)
  54. for idx, b := range clientSend {
  55. clientExpected[idx] = b ^ 'c'
  56. }
  57. assert.Bytes(clientReceived).Equals(clientExpected)
  58. wg.Done()
  59. }()
  60. }
  61. wg.Wait()
  62. for i := 0; i < 60 && listerner.ActiveConnections() > 0; i++ {
  63. time.Sleep(500 * time.Millisecond)
  64. }
  65. assert.Int(listerner.ActiveConnections()).Equals(0)
  66. listerner.Close()
  67. close(conns)
  68. }