datalink.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package network
  2. import (
  3. "net"
  4. "bet24.com/log"
  5. "bet24.com/public"
  6. )
  7. const (
  8. HEADER uint8 = 0xAA
  9. CMD_PING uint8 = 5
  10. MAX_BUFFER_SIZE int = 4096
  11. )
  12. type DataLink struct {
  13. recvBuffer []byte
  14. }
  15. func NewDataLink() *DataLink {
  16. var obj = new(DataLink)
  17. obj.recvBuffer = nil
  18. return obj
  19. }
  20. func (this *DataLink) OnDataArrive(buffer []byte, onCommand func([]byte)) bool {
  21. if buffer == nil {
  22. return true
  23. }
  24. if this.recvBuffer != nil {
  25. if buffer != nil {
  26. buffer = append(this.recvBuffer, buffer...)
  27. } else {
  28. buffer = this.recvBuffer
  29. }
  30. this.recvBuffer = nil
  31. }
  32. totalLen := len(buffer)
  33. if totalLen == 0 {
  34. return true
  35. }
  36. // 不够包头
  37. if totalLen < 4 {
  38. this.appendTemBuffer(buffer)
  39. return true
  40. }
  41. // 解析长度
  42. var ba *public.ByteArray = public.CreateByteArray(buffer)
  43. ph, _ := ba.ReadUInt8()
  44. if ph != HEADER {
  45. log.Debug("handleData 第一个字节不是%d %d\n", HEADER, ph)
  46. return false
  47. }
  48. cmdID, _ := ba.ReadUInt8()
  49. cmdLen, _ := ba.ReadUInt16()
  50. if ba.Available() < int(cmdLen) {
  51. // 粘包
  52. this.appendTemBuffer(buffer)
  53. return true
  54. }
  55. log.Debug("handleData cmdID = %d,cmdLen = %d,totalLen = %d", cmdID, cmdLen, totalLen)
  56. // 是否第一个包
  57. cmdBuffer := make([]byte, cmdLen+1)
  58. cmdBuffer[0] = cmdID
  59. ba.ReadBytes(cmdBuffer, int(cmdLen), 1)
  60. onCommand(cmdBuffer)
  61. nAvailable := ba.Available()
  62. if nAvailable > 0 {
  63. available := make([]byte, nAvailable)
  64. ba.ReadBytes(available, nAvailable, 0)
  65. this.appendTemBuffer(available)
  66. return this.OnDataArrive([]byte{}, onCommand)
  67. }
  68. return true
  69. }
  70. func (this *DataLink) appendTemBuffer(buffer []byte) {
  71. if this.recvBuffer == nil {
  72. this.recvBuffer = buffer[:]
  73. return
  74. }
  75. this.recvBuffer = append(this.recvBuffer, buffer...)
  76. }
  77. func SendData(data []byte, conn net.Conn) {
  78. log.Debug("datalink SendData len = %d", len(data))
  79. var buf []byte
  80. var ba *public.ByteArray = public.CreateByteArray(buf)
  81. dataLen := 0
  82. if data != nil {
  83. dataLen = len(data)
  84. }
  85. ba.WriteUInt8(HEADER)
  86. ba.WriteUInt8(0)
  87. ba.WriteInt16(int16(dataLen))
  88. if data != nil {
  89. ba.WriteBytes(data)
  90. }
  91. conn.Write(ba.Bytes())
  92. }