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.

67 lines
1.5 KiB

  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net"
  6. "zinx/znet"
  7. )
  8. //只是负责测试datapack拆包,封包功能
  9. func main() {
  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. for {
  18. conn, err := listener.Accept()
  19. if err != nil {
  20. fmt.Println("server accept err:", err)
  21. }
  22. //处理客户端请求
  23. go func(conn net.Conn) {
  24. //创建封包拆包对象dp
  25. dp := znet.NewDataPack()
  26. for {
  27. //1 先读出流中的head部分
  28. headData := make([]byte, dp.GetHeadLen())
  29. _, err := io.ReadFull(conn, headData) //ReadFull 会把msg填充满为止
  30. if err != nil {
  31. fmt.Println("read head error")
  32. break
  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.(*znet.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. select {}
  57. }