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.

66 lines
1.5 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. fmt.Println("Client Test ... start")
  14. //3秒之后发起测试请求,给服务端开启服务的机会
  15. time.Sleep(3 * time.Second)
  16. conn,err := net.Dial("tcp", "127.0.0.1:7777")
  17. if err != nil {
  18. fmt.Println("client start err, exit!")
  19. return
  20. }
  21. for n := 3; n >= 0; n-- {
  22. //发封包message消息
  23. dp := znet.NewDataPack()
  24. msg, _ := dp.Pack(znet.NewMsgPackage(1,[]byte("Zinx V0.8 Client1 Test Message")))
  25. _, err := conn.Write(msg)
  26. if err !=nil {
  27. fmt.Println("write error err ", err)
  28. return
  29. }
  30. //先读出流中的head部分
  31. headData := make([]byte, dp.GetHeadLen())
  32. _, err = io.ReadFull(conn, headData) //ReadFull 会把msg填充满为止
  33. if err != nil {
  34. fmt.Println("read head error")
  35. break
  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.(*znet.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. time.Sleep(1*time.Second)
  56. }
  57. }