Encode create a packet.Packet from the raw bytes slice and then encode to network bytes slice Protocol refs: https://github.com/NetEase/pomelo/wiki/Communication-Protocol - -|-------- --------|- - --------|------------------------|-------- 1 byte packet type, 3 bytes packet data l
(typ packet.Type, data []byte)
| 112 | // --------|------------------------|-------- |
| 113 | // 1 byte packet type, 3 bytes packet data length(big end), and data segment |
| 114 | func Encode(typ packet.Type, data []byte) ([]byte, error) { |
| 115 | if typ < packet.Handshake || typ > packet.Kick { |
| 116 | return nil, packet.ErrWrongPacketType |
| 117 | } |
| 118 | |
| 119 | p := &packet.Packet{Type: typ, Length: len(data)} |
| 120 | buf := make([]byte, p.Length+HeadLength) |
| 121 | buf[0] = byte(p.Type) |
| 122 | |
| 123 | copy(buf[1:HeadLength], intToBytes(p.Length)) |
| 124 | copy(buf[HeadLength:], data) |
| 125 | |
| 126 | return buf, nil |
| 127 | } |
| 128 | |
| 129 | // Decode packet data length byte to int(Big end) |
| 130 | func bytesToInt(b []byte) int { |
searching dependent graphs…