github.com/v2fly/v2ray-core/v4@v4.45.2/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  	"golang.org/x/sync/errgroup"
    12  
    13  	"github.com/v2fly/v2ray-core/v4/common"
    14  	"github.com/v2fly/v2ray-core/v4/common/errors"
    15  	"github.com/v2fly/v2ray-core/v4/common/net"
    16  	"github.com/v2fly/v2ray-core/v4/transport/internet"
    17  	. "github.com/v2fly/v2ray-core/v4/transport/internet/kcp"
    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 internet.Connection) {
    25  		go func(c internet.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  }