duandaoji3992 2016-04-14 09:51
浏览 38
已采纳

使用协议缓冲区发送二进制数据的正确方法是什么?

After using the protogen tool, I have a message type for sending messages:

type File struct {
    Info string `protobuf:"bytes,1,opt,name=info,json=info" json:"info,omitempty"`
    BytesValues []byte  `protobuf:"bytes,2,opt,name=bytes_values,json=bytesValues,proto3" json:"bytes_values,omitempty"`
}

I am trying to send some binary data using the BytesValues field like so:

filePath := filepath.Join("test", "myfile.bin")

f, _ := ioutil.ReadFile(filePath) // error return value ignored for brevity

msg := File{BytesValues: f}

body, _ := proto.Marshal(msg) // encode

The server seems to have problems decoding the message I am sending to it. Is this the correct way to send binary data using a []byte field with protocol buffers?

  • 写回答

1条回答 默认 最新

  • doujing5150 2016-04-22 01:38
    关注

    In my case, the problem was actually the server not reading the raw bytes from the correct field.

    The correct way to send raw bytes is to just set the bytes to the field. There is no need to encode the bytes in any way because protocol buffers is a binary format.

    filePath := filepath.Join("test", "myfile.bin")
    
    f, _ := ioutil.ReadFile(filePath) // error return value ignored for brevity
    
    msg := File{BytesValues: f}
    
    body, _ := proto.Marshal(msg) // encode
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示