github.com/ipfans/trojan-go@v0.11.0/tunnel/dokodemo/dokodemo_test.go (about)

     1  package dokodemo
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net"
     7  	"sync"
     8  	"testing"
     9  
    10  	"github.com/ipfans/trojan-go/common"
    11  	"github.com/ipfans/trojan-go/config"
    12  	"github.com/ipfans/trojan-go/test/util"
    13  )
    14  
    15  func TestDokodemo(t *testing.T) {
    16  	cfg := &Config{
    17  		LocalHost:  "127.0.0.1",
    18  		LocalPort:  common.PickPort("tcp", "127.0.0.1"),
    19  		TargetHost: "127.0.0.1",
    20  		TargetPort: common.PickPort("tcp", "127.0.0.1"),
    21  		UDPTimeout: 30,
    22  	}
    23  	ctx := config.WithConfig(context.Background(), Name, cfg)
    24  	s, err := NewServer(ctx, nil)
    25  	common.Must(err)
    26  	conn1, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", cfg.LocalPort))
    27  	common.Must(err)
    28  	conn2, err := s.AcceptConn(nil)
    29  	common.Must(err)
    30  	if !util.CheckConn(conn1, conn2) {
    31  		t.Fail()
    32  	}
    33  	conn1.Close()
    34  	conn2.Close()
    35  
    36  	wg := sync.WaitGroup{}
    37  	wg.Add(1)
    38  
    39  	packet1, err := net.ListenPacket("udp", "")
    40  	common.Must(err)
    41  	common.Must2(packet1.(*net.UDPConn).WriteToUDP([]byte("hello1"), &net.UDPAddr{
    42  		IP:   net.ParseIP("127.0.0.1"),
    43  		Port: cfg.LocalPort,
    44  	}))
    45  	packet2, err := s.AcceptPacket(nil)
    46  	common.Must(err)
    47  	buf := [100]byte{}
    48  	n, m, err := packet2.ReadWithMetadata(buf[:])
    49  	common.Must(err)
    50  	if m.Address.Port != cfg.TargetPort {
    51  		t.Fail()
    52  	}
    53  	if string(buf[:n]) != "hello1" {
    54  		t.Fail()
    55  	}
    56  	fmt.Println(n, m, string(buf[:n]))
    57  
    58  	if !util.CheckPacket(packet1, packet2) {
    59  		t.Fail()
    60  	}
    61  
    62  	packet3, err := net.ListenPacket("udp", "")
    63  	common.Must(err)
    64  	common.Must2(packet3.(*net.UDPConn).WriteToUDP([]byte("hello2"), &net.UDPAddr{
    65  		IP:   net.ParseIP("127.0.0.1"),
    66  		Port: cfg.LocalPort,
    67  	}))
    68  	packet4, err := s.AcceptPacket(nil)
    69  	common.Must(err)
    70  	n, m, err = packet4.ReadWithMetadata(buf[:])
    71  	common.Must(err)
    72  	if m.Address.Port != cfg.TargetPort {
    73  		t.Fail()
    74  	}
    75  	if string(buf[:n]) != "hello2" {
    76  		t.Fail()
    77  	}
    78  	fmt.Println(n, m, string(buf[:n]))
    79  
    80  	wg = sync.WaitGroup{}
    81  	wg.Add(2)
    82  	go func() {
    83  		if !util.CheckPacket(packet3, packet4) {
    84  			t.Fail()
    85  		}
    86  		wg.Done()
    87  	}()
    88  	go func() {
    89  		if !util.CheckPacket(packet1, packet2) {
    90  			t.Fail()
    91  		}
    92  		wg.Done()
    93  	}()
    94  	wg.Wait()
    95  	s.Close()
    96  }