2016-07-12 17:54:54 -04:00
|
|
|
package kcp_test
|
|
|
|
|
|
|
|
import (
|
2017-01-26 14:46:44 -05:00
|
|
|
"context"
|
2016-07-12 17:54:54 -04:00
|
|
|
"crypto/rand"
|
|
|
|
"io"
|
|
|
|
"sync"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
2017-08-29 06:56:57 -04:00
|
|
|
"v2ray.com/core/common/net"
|
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"
|
2017-10-26 15:44:22 -04:00
|
|
|
. "v2ray.com/ext/assert"
|
2016-07-12 17:54:54 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestDialAndListen(t *testing.T) {
|
2017-10-24 10:15:35 -04:00
|
|
|
assert := With(t)
|
2016-07-12 17:54:54 -04:00
|
|
|
|
2018-02-08 10:22:44 -05:00
|
|
|
listerner, err := NewListener(internet.ContextWithTransportSettings(context.Background(), &Config{}), net.LocalHostIP, net.Port(0), 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)
|
|
|
|
})
|
2017-10-24 10:15:35 -04:00
|
|
|
assert(err, IsNil)
|
2017-08-29 06:56:57 -04:00
|
|
|
port := net.Port(listerner.Addr().(*net.UDPAddr).Port)
|
2016-07-12 17:54:54 -04:00
|
|
|
|
2017-01-26 14:46:44 -05: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++ {
|
2017-08-29 06:56:57 -04:00
|
|
|
clientConn, err := DialKCP(ctx, net.UDPDestination(net.LocalHostIP, port))
|
2017-10-24 10:15:35 -04:00
|
|
|
assert(err, IsNil)
|
2016-07-12 17:54:54 -04:00
|
|
|
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)
|
2017-10-24 10:15:35 -04:00
|
|
|
assert(nBytes, Equals, len(clientReceived))
|
2016-07-12 17:54:54 -04:00
|
|
|
clientConn.Close()
|
|
|
|
|
|
|
|
clientExpected := make([]byte, 1024*1024)
|
|
|
|
for idx, b := range clientSend {
|
|
|
|
clientExpected[idx] = b ^ 'c'
|
|
|
|
}
|
2017-10-24 10:15:35 -04:00
|
|
|
assert(clientReceived, Equals, clientExpected)
|
2016-07-12 17:54:54 -04:00
|
|
|
|
|
|
|
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)
|
|
|
|
}
|
2017-10-24 10:15:35 -04:00
|
|
|
assert(listerner.ActiveConnections(), Equals, 0)
|
2016-07-12 17:54:54 -04:00
|
|
|
|
|
|
|
listerner.Close()
|
|
|
|
}
|