@@ -15,14 +15,15 @@ var (
1515)
1616
1717const (
18- packetSize = 2
18+ bodySize = 2 // 包体大小字段
19+ msgIDSize = 2 // 消息ID字段
1920)
2021
2122// 接收Length-Type-Value格式的封包流程
2223func RecvLTVPacket (reader io.Reader , maxPacketSize int ) (msg interface {}, err error ) {
2324
2425 // Size为uint16,占2字节
25- var sizeBuffer = make ([]byte , packetSize )
26+ var sizeBuffer = make ([]byte , bodySize )
2627
2728 // 持续读取Size直到读到为止
2829 _ , err = io .ReadFull (reader , sizeBuffer )
@@ -32,7 +33,7 @@ func RecvLTVPacket(reader io.Reader, maxPacketSize int) (msg interface{}, err er
3233 return
3334 }
3435
35- if len (sizeBuffer ) < packetSize {
36+ if len (sizeBuffer ) < bodySize {
3637 return nil , ErrMinPacket
3738 }
3839
@@ -54,13 +55,13 @@ func RecvLTVPacket(reader io.Reader, maxPacketSize int) (msg interface{}, err er
5455 return
5556 }
5657
57- if len (sizeBuffer ) < packetSize {
58+ if len (sizeBuffer ) < bodySize {
5859 return nil , ErrShortMsgID
5960 }
6061
6162 msgid := binary .LittleEndian .Uint16 (body )
6263
63- msgData := body [2 :]
64+ msgData := body [msgIDSize :]
6465
6566 // 将字节数组和消息ID用户解出消息
6667 msg , _ , err = codec .DecodeMessage (int (msgid ), msgData )
@@ -98,16 +99,16 @@ func SendLTVPacket(writer io.Writer, ctx cellnet.ContextSet, data interface{}) e
9899 msgID = meta .ID
99100 }
100101
101- pkt := make ([]byte , 2 + 2 + len (msgData ))
102+ pkt := make ([]byte , bodySize + msgIDSize + len (msgData ))
102103
103104 // Length
104- binary .LittleEndian .PutUint16 (pkt , uint16 (2 + len (msgData )))
105+ binary .LittleEndian .PutUint16 (pkt , uint16 (msgIDSize + len (msgData )))
105106
106107 // Type
107- binary .LittleEndian .PutUint16 (pkt [2 :], uint16 (msgID ))
108+ binary .LittleEndian .PutUint16 (pkt [msgIDSize :], uint16 (msgID ))
108109
109110 // Value
110- copy (pkt [2 + 2 :], msgData )
111+ copy (pkt [bodySize + msgIDSize :], msgData )
111112
112113 // 将数据写入Socket
113114 err := WriteFull (writer , pkt )
0 commit comments