diff --git a/packet/const.go b/packet/const.go index 8772508..72dcd9f 100644 --- a/packet/const.go +++ b/packet/const.go @@ -1,5 +1,7 @@ package packet +import "errors" + const ( //publish类型 缓存最小大小 PUBLISH_CACHE_MINLENGTH = 1024 * 1024 * 1024 @@ -120,3 +122,10 @@ const ( PARSE_NOT_ENOUGH_LACK //解析字节不够,下次提供新增字节 PARSE_REMAINDER //剩余字节 ) + +var ( + // ErrNoTopic PUBLISH 未设置主题 + ErrNoTopic = errors.New("PUBLISH 未设置主题") + // 主题包含U+0000字符 + ErrTopicU0000 = errors.New("主题包含U+0000字符") +) diff --git a/packet/packet_test.go b/packet/packet_test.go index 8c215e6..ac27dc7 100644 --- a/packet/packet_test.go +++ b/packet/packet_test.go @@ -82,7 +82,7 @@ func TestPublishPacketAndUnPacket(t *testing.T) { newconn.remlen = int(datalen) fmt.Printf("%X\n", tmp[1+clen:]) newconn.UnPacket(tmp[0], tmp[1+clen:]) - fmt.Printf("解析后结果:\n%s", newconn) + fmt.Printf("解析后结果:\n%v", newconn) } diff --git a/packet/publish.go b/packet/publish.go index f023ab2..0820241 100644 --- a/packet/publish.go +++ b/packet/publish.go @@ -5,7 +5,6 @@ package packet import ( - "errors" "fmt" "io" "time" @@ -209,7 +208,7 @@ func formatPayload(payload []byte) string { return fmt.Sprintf("(%d)%X", len(payload), payload[0:n]) } func (c *Publish) String() string { - return fmt.Sprintf("PUBLISH重发标志:%t 服务质量等级(Qos):%d 保留标志:%t 主题名:%s 报文标志:%d 接收时间:%v有效载荷:%s", c.GetDupFlag(), c.GetQos(), c.GetRetain(), c.topic, c.packetId, c.ReciveStartTime, formatPayload(c.payload)) + return fmt.Sprintf("PUBLISH DUP:%t QoS:%d Retain:%t Topic:%s id:%d time:%v payload:%s", c.GetDupFlag(), c.GetQos(), c.GetRetain(), c.topic, c.packetId, c.ReciveStartTime, formatPayload(c.payload)) } //解包 @@ -217,6 +216,9 @@ func (c *Publish) UnPacket(header byte, msg []byte) error { c.cache = false c.remlen = len(msg) + if c.remlen < 2 { + return ErrNoTopic + } // c.SetRetain(header&0x1 == 0x1) // c.SetQos(QoS(header >> 1 & 0x3)) // c.SetDupFlag(header&0x8 == 0x8) @@ -232,7 +234,7 @@ func (c *Publish) UnPacket(header byte, msg []byte) error { } if !util.VerifyZeroByMqtt([]rune(c.GetTopicByString())) { - return errors.New("主题包含U+0000字符关闭连接") + return ErrTopicU0000 } //c.setBuffByRemdata(msg) return nil