[Go] stick package and unpacking problems packet lightweight server framework the tcp

Tcp data transmitted in the form of transport stream, so there is no way to determine where to be regarded as the end of his message, so there will be a problem stick package, multiple packages glued together

Such forms can be used to solve a custom, a message is divided into head + body head comprises a length and a data number, length and number of data types are uint32 i.e. 32 occupies 4 bytes, a total of eight words head occupies festival

A message package structure as a data entity, such as the following, three number data length attribute

package znet

type Message struct {
    Id     uint32
    Data   []byte
    MsgLen uint32
}

func NewMessage() *Message {
    m := &Message{}
    return m
}
func (m *Message) GetId() uint32 {
    return m.Id
}
func (m *Message) GetData() []byte {
    return m.Data
}
func (m *Message) GetMsgLen() uint32 {
    return m.MsgLen
}
func (m *Message) SetId(id uint32) {
    m.Id = id
}
func (m *Message) SetData(data []byte) {
    m.Data = data
}
func (m *Message) SetMsgLen(len uint32) {
    m.MsgLen = len
}

A packet unpacking the package structure, the method comprising unpacking packet, the packet length is to write, write serial number, write transactions; unpack just gets the length and number, and then take the next data

package znet

import "zinx/zinterface"

import "bytes"

import "encoding/binary"

type DataPack struct {
}

func NewDataPack() *DataPack {
    dp := &DataPack{}
    return dp
}
func (dp *DataPack) Pack(m zinterface.IMessage) ([]byte, error) {
    dataBuff := bytes.NewBuffer([]byte{})
    binary.Write(dataBuff, binary.LittleEndian, m.GetMsgLen())
    binary.Write(dataBuff, binary.LittleEndian, m.GetId())
    binary.Write(dataBuff, binary.LittleEndian, m.GetData())
    return dataBuff.Bytes(), nil
}
func (dp *DataPack) Unpack(d []byte) (zinterface.IMessage, error) {
    m := NewMessage()
    r := bytes.NewReader(d)
    binary.Read(r, binary.LittleEndian, &m.MsgLen)
    binary.Read(r, binary.LittleEndian, &m.Id)
    return m, nil
}

Test, the first packet and then unpack

    body:=[]byte("nihao")
    m:=znet.NewMessage()
    m.SetId(888)
    m.SetData(body)
    m.SetMsgLen(uint32(len(body)))
    log.Println(m)

    dp:=znet.NewDataPack()
    dataPack,_:=dp.Pack(m)
    log.Println(dataPack)

    m2,_:=dp.Unpack(dataPack)
    log.Println(m2)

2019/12/17 15:42:30 &{888 [110 105 104 97 111] 5}
2019/12/17 15:42:30 [5 0 0 0 120 3 0 0 110 105 104 97 111]
2019/12/17 15:42:30 &{888 [] 5}

The result is that the above way, the solution can go out with the

 

Guess you like

Origin www.cnblogs.com/taoshihan/p/12057619.html