doulierong0334 2014-05-31 12:29 采纳率: 100%
浏览 77
已采纳

Golang数据包结构返回缓冲区

I have made a packet package with a packet structure inside like so:

//A packet buffer object
package Packet

import (
    "bytes"
    "encoding/binary"
)

type Packet struct {
    buffer bytes.Buffer
}

func (p Packet) GetBytes() []byte {
    return p.buffer.Bytes()
}

func (p Packet) AddString(s string) {
    p.buffer.Write([]byte(s))
}

func (p Packet) AddInt(i_ int) {
    //Convert int to byte
    b := make([]byte, 2)
    binary.LittleEndian.PutUint16(b, uint16(i_))
    //Push byte to buffer
    p.buffer.Write([]byte(b))
}

func (p Packet) AddByte(b []byte) {
    p.buffer.Write(b)
}

This is the session package that uses the packet structure to form packets and send them to the client

package Session

type MapleSession struct {
    connection net.Conn
    EncryptIV, DecryptIV []byte
    isConnected bool
}

func (session *MapleSession) Run(conn net.Conn) { 
    //Display where the new connection is coming from
    session.connection = conn
    fmt.Println("Client connected from:", session.connection.RemoteAddr())

    //Set the user connected variable on
    session.isConnected = true

    //Send Handshake
    packet := MaplePacket.CreateHandShake(&session.EncryptIV, &session.DecryptIV, 40, "", []byte("0x05"))
    session.connection.Write(packet)
}

This is the MaplePacket package that creates the packets to send to the client that are requested from the session package

package MaplePacket

func CreateHandShake (eIV, dIV *[]byte, version int, location string, locale []byte) []byte{
    packet := Packet.Packet{}

    //Create IVs
    *eIV = (make([]byte, 4))
    n1, _ := rand.Read(*eIV)
    *dIV = (make([]byte, 4))
    n2, _ := rand.Read(*dIV)

    if (n1 + n2 < 8) {
        fmt.Println("Error in IV generation")
    }    

    //Create the packet
    packet.AddInt(version)
    packet.AddString(location)
    packet.AddByte(*dIV)
    packet.AddByte(*eIV)
    packet.AddByte(locale)

    fmt.Println(packet.GetBytes())

    return packet.GetBytes()
}

However when creating a packet like in the example above and adding values, the Packet.GetBytes() returns an empty array. Is bytes.Buffer the correct way to go about this is? Or am I going completely wrong in how I am approaching this?

  • 写回答

1条回答 默认 最新

  • dtbl1231 2014-05-31 13:02
    关注

    Go passes all arguments, including receivers, by value.

    Try using pointer receivers: (p *Packet). bytes.Buffer contains state information which is being discarded.


    package bytes

    // Simple byte buffer for marshaling data.
    // A Buffer is a variable-sized buffer of bytes with Read and Write methods.
    // The zero value for Buffer is an empty buffer ready to use.
    type Buffer struct {
      buf       []byte            // contents are the bytes buf[off : len(buf)]
      off       int               // read at &buf[off], write at &buf[len(buf)]
      runeBytes [utf8.UTFMax]byte // avoid allocation of slice on each WriteByte or Rune
      bootstrap [64]byte          // memory to hold first slice; helps small buffers (Printf) avoid allocation.
      lastRead  readOp            // last read operation, so that Unread* can work correctly.
    }
    

    The Go Programming Language

    Effective Go

    Methods

    Pointers vs. Values

    The rule about pointers vs. values for receivers is that value methods can be invoked on pointers and values, but pointer methods can only be invoked on pointers. This is because pointer methods can modify the receiver; invoking them on a copy of the value would cause those modifications to be discarded.

    Your type Package type is equivalent to the following.

    type Packet struct {
        buffer /* bytes.Buffer */ struct {
        buf       []byte            // contents are the bytes buf[off : len(buf)]
        off       int               // read at &buf[off], write at &buf[len(buf)]
        runeBytes [utf8.UTFMax]byte // avoid allocation of slice on each WriteByte or Rune
        bootstrap [64]byte          // memory to hold first slice; helps small buffers (Printf) avoid allocation.
        lastRead  readOp            // last read operation, so that Unread* can work correctly.
    }
    

    You pass a copy (by value) of a Package type variable to the methods. The copy is updated to reflect the new state and, upon return is discarded.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置