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 51寻迹小车定点寻迹
  • ¥15 爬虫爬取网站的一些信息
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件