udp_test.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package network
  2. import (
  3. "fmt"
  4. "strings"
  5. "sync"
  6. "testing"
  7. "time"
  8. )
  9. const (
  10. testUDPServerAddress = "127.0.0.1:10060"
  11. testUDPServerTimeout = time.Second
  12. testUDPServerReceiveBufferSize = 1024
  13. testUDPClientTimeout = time.Second
  14. testUDPClientReceiveBufferSize = 1024
  15. )
  16. func TestUDP(t *testing.T) {
  17. server := &UDPServer{}
  18. err := server.Connect(testUDPServerAddress, NewUDPServerOptions(
  19. WithUDPServerReadTimeout(testUDPServerTimeout),
  20. WithUDPServerWriteTimeout(testUDPServerTimeout),
  21. WithUDPServerReceiveBufferSize(testUDPServerReceiveBufferSize),
  22. WithUDPServerRequestCallback(func(dataReader *DataReader) *DataReader {
  23. requestBytes, err := dataReader.Bytes(dataReader.Len())
  24. if err != nil {
  25. t.Fatal(err)
  26. return nil
  27. }
  28. responseWriter := NewDataWriter()
  29. err = responseWriter.Bytes([]byte(strings.ToUpper(string(requestBytes))))
  30. if err != nil {
  31. t.Fatal(err)
  32. return nil
  33. }
  34. return responseWriter.ToReader()
  35. }),
  36. ))
  37. if err != nil {
  38. t.Fatal(err)
  39. }
  40. defer server.Disconnect()
  41. wg := &sync.WaitGroup{}
  42. wg.Add(2)
  43. client := &UDPClient{}
  44. err = client.Connect(testUDPServerAddress, NewUDPClientOptions(
  45. WithUDPClientReadTimeout(testUDPClientTimeout),
  46. WithUDPClientWriteTimeout(testUDPClientTimeout),
  47. WithUDPClientReceiveBufferSize(testUDPClientReceiveBufferSize),
  48. WithUDPClientRequestNonBlockCount(2),
  49. WithUDPClientResponseCallback(func(dataReader *DataReader) {
  50. requestBytes, err := dataReader.Bytes(dataReader.Len())
  51. if err != nil {
  52. t.Fatal(err)
  53. return
  54. }
  55. fmt.Println(string(requestBytes))
  56. wg.Done()
  57. }),
  58. ))
  59. if err != nil {
  60. t.Fatal(err)
  61. }
  62. defer client.Disconnect()
  63. client.Send([]byte("test1"))
  64. client.Send([]byte("test2"))
  65. wg.Wait()
  66. }