v2ray-core/transport/internet/kcp/kcp_test.go

81 lines
1.8 KiB
Go
Raw Normal View History

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