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 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并