tcp_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package network
  2. import (
  3. "fmt"
  4. "strings"
  5. "sync"
  6. "testing"
  7. "time"
  8. )
  9. const (
  10. testTCPServerAddress = "127.0.0.1:10060"
  11. testTCPServerTimeout = time.Second
  12. testTCPServerReceiveBufferSize = 1024
  13. testTCPClientTimeout = time.Second
  14. testTCPClientReceiveBufferSize = 1024
  15. )
  16. func TestTCP(t *testing.T) {
  17. server := &TCPServer{}
  18. err := server.Connect(testTCPServerAddress, NewTCPServerOptions(
  19. WithTCPServerReadTimeout(testTCPServerTimeout),
  20. WithTCPServerWriteTimeout(testTCPServerTimeout),
  21. WithTCPServerReceiveBufferSize(testTCPServerReceiveBufferSize),
  22. WithTCPServerRequestCallback(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 func(server *TCPServer) {
  41. err := server.Disconnect()
  42. if err != nil {
  43. t.Fatal(err)
  44. }
  45. }(server)
  46. wg := &sync.WaitGroup{}
  47. wg.Add(2)
  48. client := &TCPClient{}
  49. err = client.Connect(testTCPServerAddress, NewTCPClientOptions(
  50. WithTCPClientReadTimeout(testTCPClientTimeout),
  51. WithTCPClientWriteTimeout(testTCPClientTimeout),
  52. WithTCPClientReceiveBufferSize(testTCPClientReceiveBufferSize),
  53. WithTCPClientRequestNonBlockCount(2),
  54. WithTCPClientResponseCallback(func(dataReader *DataReader) bool {
  55. defer wg.Done()
  56. requestBytes, err := dataReader.Bytes(dataReader.Len())
  57. if err != nil {
  58. t.Fatal(err)
  59. return true
  60. }
  61. fmt.Println(string(requestBytes))
  62. return true
  63. }),
  64. ))
  65. if err != nil {
  66. t.Fatal(err)
  67. }
  68. defer client.Disconnect()
  69. client.Send([]byte("test1"))
  70. client.Send([]byte("test2"))
  71. wg.Wait()
  72. }