You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

115 lines
2.5 KiB

4 years ago
4 years ago
4 years ago
  1. package znet
  2. import (
  3. "fmt"
  4. "io"
  5. "net"
  6. "testing"
  7. "time"
  8. )
  9. // run in terminal:
  10. // go test -v ./znet -run=TestDataPack
  11. //只是负责测试datapack拆包,封包功能
  12. func TestDataPack(t *testing.T) {
  13. //创建socket TCP Server
  14. listener, err := net.Listen("tcp", "127.0.0.1:7777")
  15. if err != nil {
  16. fmt.Println("server listen err:", err)
  17. return
  18. }
  19. //创建服务器gotoutine,负责从客户端goroutine读取粘包的数据,然后进行解析
  20. go func() {
  21. for {
  22. conn, err := listener.Accept()
  23. if err != nil {
  24. fmt.Println("server accept err:", err)
  25. }
  26. //处理客户端请求
  27. go func(conn net.Conn) {
  28. //创建封包拆包对象dp
  29. dp := NewDataPack()
  30. for {
  31. //1 先读出流中的head部分
  32. headData := make([]byte, dp.GetHeadLen())
  33. _, err := io.ReadFull(conn, headData) //ReadFull 会把msg填充满为止
  34. if err != nil {
  35. fmt.Println("read head error")
  36. }
  37. //将headData字节流 拆包到msg中
  38. msgHead, err := dp.Unpack(headData)
  39. if err != nil {
  40. fmt.Println("server unpack err:", err)
  41. return
  42. }
  43. if msgHead.GetDataLen() > 0 {
  44. //msg 是有data数据的,需要再次读取data数据
  45. msg := msgHead.(*Message)
  46. msg.Data = make([]byte, msg.GetDataLen())
  47. //根据dataLen从io中读取字节流
  48. _, err := io.ReadFull(conn, msg.Data)
  49. if err != nil {
  50. fmt.Println("server unpack data err:", err)
  51. return
  52. }
  53. fmt.Println("==> Recv Msg: ID=", msg.ID, ", len=", msg.DataLen, ", data=", string(msg.Data))
  54. }
  55. }
  56. }(conn)
  57. }
  58. }()
  59. //客户端goroutine,负责模拟粘包的数据,然后进行发送
  60. go func() {
  61. conn, err := net.Dial("tcp", "127.0.0.1:7777")
  62. if err != nil {
  63. fmt.Println("client dial err:", err)
  64. return
  65. }
  66. //创建一个封包对象 dp
  67. dp := NewDataPack()
  68. //封装一个msg1包
  69. msg1 := &Message{
  70. ID: 0,
  71. DataLen: 5,
  72. Data: []byte{'h', 'e', 'l', 'l', 'o'},
  73. }
  74. sendData1, err := dp.Pack(msg1)
  75. if err != nil {
  76. fmt.Println("client pack msg1 err:", err)
  77. return
  78. }
  79. msg2 := &Message{
  80. ID: 1,
  81. DataLen: 7,
  82. Data: []byte{'w', 'o', 'r', 'l', 'd', '!', '!'},
  83. }
  84. sendData2, err := dp.Pack(msg2)
  85. if err != nil {
  86. fmt.Println("client temp msg2 err:", err)
  87. return
  88. }
  89. //将sendData1,和 sendData2 拼接一起,组成粘包
  90. sendData1 = append(sendData1, sendData2...)
  91. //向服务器端写数据
  92. conn.Write(sendData1)
  93. }()
  94. //客户端阻塞
  95. select {
  96. case <-time.After(time.Second):
  97. return
  98. }
  99. }