1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-23 10:37:09 -05:00
v2fly/transport/internet/kcp/kcp_test.go

86 lines
2.0 KiB
Go
Raw Normal View History

2016-07-12 17:54:54 -04:00
package kcp_test
import (
"context"
2016-07-12 17:54:54 -04:00
"crypto/rand"
"io"
"testing"
"time"
2019-02-10 09:02:28 -05:00
"github.com/google/go-cmp/cmp"
"golang.org/x/sync/errgroup"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/errors"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/transport/internet"
. "github.com/v2fly/v2ray-core/v5/transport/internet/kcp"
2016-07-12 17:54:54 -04:00
)
func TestDialAndListen(t *testing.T) {
2021-12-23 00:14:43 -05:00
listener, err := NewListener(context.Background(), net.LocalHostIP, net.Port(0), &internet.MemoryStreamConfig{
2018-09-07 08:50:25 -04:00
ProtocolName: "mkcp",
ProtocolSettings: &Config{},
}, func(conn internet.Connection) {
2017-05-08 18:01:15 -04:00
go func(c internet.Connection) {
payload := make([]byte, 4096)
for {
nBytes, err := c.Read(payload)
if err != nil {
break
}
for idx, b := range payload[:nBytes] {
payload[idx] = b ^ 'c'
}
c.Write(payload[:nBytes])
}
c.Close()
}(conn)
})
2019-02-02 16:19:30 -05:00
common.Must(err)
2021-12-23 00:14:43 -05:00
defer listener.Close()
2019-02-10 09:02:28 -05:00
2021-12-23 00:14:43 -05:00
port := net.Port(listener.Addr().(*net.UDPAddr).Port)
2016-07-12 17:54:54 -04:00
2019-02-10 09:02:28 -05:00
var errg errgroup.Group
2016-07-12 17:54:54 -04:00
for i := 0; i < 10; i++ {
2019-02-10 09:02:28 -05:00
errg.Go(func() error {
clientConn, err := DialKCP(context.Background(), net.UDPDestination(net.LocalHostIP, port), &internet.MemoryStreamConfig{
ProtocolName: "mkcp",
ProtocolSettings: &Config{},
})
if err != nil {
return err
}
defer clientConn.Close()
2016-07-12 17:54:54 -04:00
clientSend := make([]byte, 1024*1024)
rand.Read(clientSend)
2016-07-14 15:31:54 -04:00
go clientConn.Write(clientSend)
2016-07-12 17:54:54 -04:00
clientReceived := make([]byte, 1024*1024)
2019-02-10 09:02:28 -05:00
common.Must2(io.ReadFull(clientConn, clientReceived))
2016-07-12 17:54:54 -04:00
clientExpected := make([]byte, 1024*1024)
for idx, b := range clientSend {
clientExpected[idx] = b ^ 'c'
}
2019-02-10 09:02:28 -05:00
if r := cmp.Diff(clientReceived, clientExpected); r != "" {
return errors.New(r)
}
return nil
})
}
2016-07-12 17:54:54 -04:00
2019-02-10 09:02:28 -05:00
if err := errg.Wait(); err != nil {
t.Fatal(err)
2016-07-12 17:54:54 -04:00
}
2021-12-23 00:14:43 -05:00
for i := 0; i < 60 && listener.ActiveConnections() > 0; i++ {
2016-11-28 16:05:57 -05:00
time.Sleep(500 * time.Millisecond)
}
2021-12-23 00:14:43 -05:00
if v := listener.ActiveConnections(); v != 0 {
2019-02-10 09:02:28 -05:00
t.Error("active connections: ", v)
}
2016-07-12 17:54:54 -04:00
}