1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- package network
- import (
- "fmt"
- "strings"
- "sync"
- "testing"
- "time"
- )
- const (
- testUDPServerAddress = "127.0.0.1:10060"
- testUDPServerTimeout = time.Second
- testUDPServerReceiveBufferSize = 1024
- testUDPClientTimeout = time.Second
- testUDPClientReceiveBufferSize = 1024
- )
- func TestUDP(t *testing.T) {
- server := &UDPServer{}
- err := server.Connect(testUDPServerAddress, NewUDPServerOptions(
- WithUDPServerReadTimeout(testUDPServerTimeout),
- WithUDPServerWriteTimeout(testUDPServerTimeout),
- WithUDPServerReceiveBufferSize(testUDPServerReceiveBufferSize),
- WithUDPServerRequestCallback(func(dataReader *DataReader) *DataReader {
- requestBytes, err := dataReader.Bytes(dataReader.Len())
- if err != nil {
- t.Fatal(err)
- return nil
- }
- responseWriter := NewDataWriter()
- err = responseWriter.Bytes([]byte(strings.ToUpper(string(requestBytes))))
- if err != nil {
- t.Fatal(err)
- return nil
- }
- return responseWriter.ToReader()
- }),
- ))
- if err != nil {
- t.Fatal(err)
- }
- defer server.Disconnect()
- wg := &sync.WaitGroup{}
- wg.Add(2)
- client := &UDPClient{}
- err = client.Connect(testUDPServerAddress, NewUDPClientOptions(
- WithUDPClientReadTimeout(testUDPClientTimeout),
- WithUDPClientWriteTimeout(testUDPClientTimeout),
- WithUDPClientReceiveBufferSize(testUDPClientReceiveBufferSize),
- WithUDPClientRequestNonBlockCount(2),
- WithUDPClientResponseCallback(func(dataReader *DataReader) {
- requestBytes, err := dataReader.Bytes(dataReader.Len())
- if err != nil {
- t.Fatal(err)
- return
- }
- fmt.Println(string(requestBytes))
- wg.Done()
- }),
- ))
- if err != nil {
- t.Fatal(err)
- }
- defer client.Disconnect()
- client.Send([]byte("test1"))
- client.Send([]byte("test2"))
- wg.Wait()
- }
|