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

94 lines
2.0 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"
2016-12-15 10:51:09 +00:00
"v2ray.com/core/common/serial"
2016-08-20 18:55:45 +00:00
"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)
2016-10-02 21:43:58 +00:00
listerner, err := NewListener(v2net.LocalHostIP, v2net.Port(0), internet.ListenOptions{
Stream: &internet.StreamConfig{
Protocol: internet.TransportProtocol_MKCP,
TransportSettings: []*internet.TransportConfig{
2016-10-02 21:43:58 +00:00
{
Protocol: internet.TransportProtocol_MKCP,
2016-12-15 10:51:09 +00:00
Settings: serial.ToTypedMessage(&Config{}),
2016-10-02 21:43:58 +00:00
},
},
},
})
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() {
for {
conn, err := listerner.Accept()
if err != nil {
break
}
go func() {
2016-07-13 07:19:51 +00:00
payload := make([]byte, 4096)
2016-07-12 21:54:54 +00:00
for {
nBytes, err := conn.Read(payload)
if err != nil {
break
}
for idx, b := range payload[:nBytes] {
payload[idx] = b ^ 'c'
}
conn.Write(payload[:nBytes])
}
conn.Close()
}()
}
}()
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()
}