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.

64 lines
1.3 KiB

  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net"
  6. "time"
  7. "github.com/aceld/zinx/znet"
  8. )
  9. /*
  10. 模拟客户端
  11. */
  12. func main() {
  13. conn, err := net.Dial("tcp", "127.0.0.1:8999")
  14. if err != nil {
  15. fmt.Println("client start err, exit!", err)
  16. return
  17. }
  18. for {
  19. //发封包message消息
  20. dp := znet.NewDataPack()
  21. msg, _ := dp.Pack(znet.NewMsgPackage(0, []byte("Zinx client Demo Test MsgID=0, [Ping]")))
  22. _, err := conn.Write(msg)
  23. if err != nil {
  24. fmt.Println("write error err ", err)
  25. return
  26. }
  27. //先读出流中的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("==> Test Router:[Ping] Recv Msg: ID=", msg.Id ", len=", msg.DataLen, ", data=", string(msg.Data))
  51. }
  52. time.Sleep(1 * time.Second)
  53. }
  54. }