dongxichan8627 2014-05-20 18:51
浏览 42
已采纳

正确的惯用字节缓冲区读写

I have a net/socket open. I need to read a structured protocol off the wire. Ie I have

messagelength|type|value|type|value ...

where messagelength is 4 bytes, type one byte, value depends on type,...

I am trying to work out the no-brainer way of doing this in go. I am swamped by io,bufio,encoding... I cant find the right place to start and cant find samples. Looking for ReadInt32, ReadByte,....

Next thing - i need to assemble a reply -> WriteInt32, WriteString, WriteByte,....

Trying to convert python to go, python code uses struct.unpack / pack

  • 写回答

1条回答 默认 最新

  • dte66654 2014-05-20 20:32
    关注

    You can use the package encoding/binary. The only functions you will need are Read() and Write(). Here is how you use them:

    The Read() function has the following signature:

    func Read(r io.Reader, order ByteOrder, data interface{}) error
    

    This function reads from r in order ByteOrder into data. data must be a pointer to a fixed-size value (e.g. an int32, a byte or a struct with only fixed size members) or a slice of such values. If you pass a pointer to a struct, struct fields are read in without padding, data corresponding for blank fields (i.e. those named _) is read and discarded (ideal for padding).

    For your specific problem, declare a struct that matches the header of your data stream.

    type Header struct {
        Length uint32
        Type   uint8
    }
    

    Consume the header of a packet (assume big endian):

    var hdr Header
    if err = Read(connection, binary.BigEndian, &hdr); err != nil {
        // deal with read error
    }
    

    Switch over the type byte:

    switch hdr.Type {
    // for each type, read into a type-specific struct
    // ...
    }
    

    Write() is similar but writes instead of reading.

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

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: