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.

107 lines
2.3 KiB

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