github.com/xraypb/xray-core@v1.6.6/transport/internet/kcp/kcp_test.go (about) 1 package kcp_test 2 3 import ( 4 "context" 5 "crypto/rand" 6 "io" 7 "testing" 8 "time" 9 10 "github.com/google/go-cmp/cmp" 11 "github.com/xraypb/xray-core/common" 12 "github.com/xraypb/xray-core/common/errors" 13 "github.com/xraypb/xray-core/common/net" 14 "github.com/xraypb/xray-core/transport/internet" 15 . "github.com/xraypb/xray-core/transport/internet/kcp" 16 "github.com/xraypb/xray-core/transport/internet/stat" 17 "golang.org/x/sync/errgroup" 18 ) 19 20 func TestDialAndListen(t *testing.T) { 21 listerner, err := NewListener(context.Background(), net.LocalHostIP, net.Port(0), &internet.MemoryStreamConfig{ 22 ProtocolName: "mkcp", 23 ProtocolSettings: &Config{}, 24 }, func(conn stat.Connection) { 25 go func(c stat.Connection) { 26 payload := make([]byte, 4096) 27 for { 28 nBytes, err := c.Read(payload) 29 if err != nil { 30 break 31 } 32 for idx, b := range payload[:nBytes] { 33 payload[idx] = b ^ 'c' 34 } 35 c.Write(payload[:nBytes]) 36 } 37 c.Close() 38 }(conn) 39 }) 40 common.Must(err) 41 defer listerner.Close() 42 43 port := net.Port(listerner.Addr().(*net.UDPAddr).Port) 44 45 var errg errgroup.Group 46 for i := 0; i < 10; i++ { 47 errg.Go(func() error { 48 clientConn, err := DialKCP(context.Background(), net.UDPDestination(net.LocalHostIP, port), &internet.MemoryStreamConfig{ 49 ProtocolName: "mkcp", 50 ProtocolSettings: &Config{}, 51 }) 52 if err != nil { 53 return err 54 } 55 defer clientConn.Close() 56 57 clientSend := make([]byte, 1024*1024) 58 rand.Read(clientSend) 59 go clientConn.Write(clientSend) 60 61 clientReceived := make([]byte, 1024*1024) 62 common.Must2(io.ReadFull(clientConn, clientReceived)) 63 64 clientExpected := make([]byte, 1024*1024) 65 for idx, b := range clientSend { 66 clientExpected[idx] = b ^ 'c' 67 } 68 if r := cmp.Diff(clientReceived, clientExpected); r != "" { 69 return errors.New(r) 70 } 71 return nil 72 }) 73 } 74 75 if err := errg.Wait(); err != nil { 76 t.Fatal(err) 77 } 78 79 for i := 0; i < 60 && listerner.ActiveConnections() > 0; i++ { 80 time.Sleep(500 * time.Millisecond) 81 } 82 if v := listerner.ActiveConnections(); v != 0 { 83 t.Error("active connections: ", v) 84 } 85 }