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

81 lines
1.8 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"
2016-08-15 16:12:11 -04:00
"net"
2016-07-12 17:54:54 -04:00
"sync"
"testing"
"time"
2016-08-20 14:55:45 -04:00
v2net "v2ray.com/core/common/net"
"v2ray.com/core/testing/assert"
2016-09-30 10:53:40 -04:00
"v2ray.com/core/transport/internet"
2016-08-20 14:55:45 -04:00
. "v2ray.com/core/transport/internet/kcp"
2016-07-12 17:54:54 -04:00
)
func TestDialAndListen(t *testing.T) {
assert := assert.On(t)
2017-02-26 08:38:41 -05:00
conns := make(chan internet.Connection, 16)
listerner, err := NewListener(internet.ContextWithTransportSettings(context.Background(), &Config{}), v2net.LocalHostIP, v2net.Port(0), conns)
2016-07-12 17:54:54 -04:00
assert.Error(err).IsNil()
2016-08-15 16:12:11 -04:00
port := v2net.Port(listerner.Addr().(*net.UDPAddr).Port)
2016-07-12 17:54:54 -04:00
go func() {
2017-02-26 08:38:41 -05:00
for conn := range conns {
go func(c internet.Connection) {
2016-07-13 03:19:51 -04:00
payload := make([]byte, 4096)
2016-07-12 17:54:54 -04:00
for {
2017-02-26 08:38:41 -05:00
nBytes, err := c.Read(payload)
2016-07-12 17:54:54 -04:00
if err != nil {
break
}
for idx, b := range payload[:nBytes] {
payload[idx] = b ^ 'c'
}
2017-02-26 08:38:41 -05:00
c.Write(payload[:nBytes])
2016-07-12 17:54:54 -04:00
}
2017-02-26 08:38:41 -05:00
c.Close()
}(conn)
2016-07-12 17:54:54 -04:00
}
}()
ctx := internet.ContextWithTransportSettings(context.Background(), &Config{})
2016-07-12 17:54:54 -04:00
wg := new(sync.WaitGroup)
for i := 0; i < 10; i++ {
clientConn, err := DialKCP(ctx, v2net.UDPDestination(v2net.LocalHostIP, port))
2016-07-12 17:54:54 -04:00
assert.Error(err).IsNil()
wg.Add(1)
go func() {
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)
nBytes, _ := io.ReadFull(clientConn, clientReceived)
assert.Int(nBytes).Equals(len(clientReceived))
clientConn.Close()
clientExpected := make([]byte, 1024*1024)
for idx, b := range clientSend {
clientExpected[idx] = b ^ 'c'
}
assert.Bytes(clientReceived).Equals(clientExpected)
wg.Done()
}()
}
wg.Wait()
2016-11-28 16:05:57 -05:00
for i := 0; i < 60 && listerner.ActiveConnections() > 0; i++ {
time.Sleep(500 * time.Millisecond)
}
2016-07-12 17:54:54 -04:00
assert.Int(listerner.ActiveConnections()).Equals(0)
listerner.Close()
2017-02-26 08:38:41 -05:00
close(conns)
2016-07-12 17:54:54 -04:00
}