trpc.group/trpc-go/trpc-go@v1.0.3/transport/server_transport_udp_test.go (about)

     1  //
     2  //
     3  // Tencent is pleased to support the open source community by making tRPC available.
     4  //
     5  // Copyright (C) 2023 THL A29 Limited, a Tencent company.
     6  // All rights reserved.
     7  //
     8  // If you have downloaded a copy of the tRPC source code from Tencent,
     9  // please note that tRPC source code is licensed under the  Apache 2.0 License,
    10  // A copy of the Apache 2.0 License is included in this file.
    11  //
    12  //
    13  
    14  package transport_test
    15  
    16  import (
    17  	"encoding/binary"
    18  	"encoding/json"
    19  	"net"
    20  	"os"
    21  	"sync"
    22  	"testing"
    23  	"time"
    24  
    25  	"github.com/stretchr/testify/assert"
    26  	"github.com/stretchr/testify/require"
    27  	"trpc.group/trpc-go/trpc-go/transport"
    28  )
    29  
    30  func Test_ServerTransport_UDP(t *testing.T) {
    31  	var addr = getFreeAddr("udp")
    32  
    33  	wg := sync.WaitGroup{}
    34  	wg.Add(1)
    35  	go func() {
    36  		defer wg.Done()
    37  		err := transport.ListenAndServe(
    38  			transport.WithListenNetwork("udp"),
    39  			transport.WithListenAddress(addr),
    40  			transport.WithHandler(&echoHandler{}),
    41  			transport.WithServerFramerBuilder(&framerBuilder{safe: true}),
    42  		)
    43  		assert.Nil(t, err)
    44  		time.Sleep(20 * time.Millisecond)
    45  	}()
    46  	wg.Wait()
    47  
    48  	req := &helloRequest{
    49  		Name: "trpc",
    50  		Msg:  "HelloWorld",
    51  	}
    52  	data, err := json.Marshal(req)
    53  	if err != nil {
    54  		t.Fatalf("json marshal fail:%v", err)
    55  	}
    56  	lenData := make([]byte, 4)
    57  	binary.BigEndian.PutUint32(lenData, uint32(len(data)))
    58  	reqData := append(lenData, data...)
    59  	reqDataBad := append(reqData, []byte("remain")...)
    60  	pc, err := net.Dial("udp", addr)
    61  	require.Nil(t, err)
    62  
    63  	// Bad request, server will not response.
    64  	pc.Write(reqDataBad)
    65  	result := make([]byte, 20)
    66  	pc.SetDeadline(time.Now().Add(100 * time.Millisecond))
    67  	_, err = pc.Read(result)
    68  	require.ErrorIs(t, err, os.ErrDeadlineExceeded)
    69  	pc.SetDeadline(time.Time{})
    70  
    71  	// Good request, server will response.
    72  	pc.Write(reqData)
    73  	_, err = pc.Read(result)
    74  	require.Nil(t, err)
    75  }