doushu5451 2019-03-16 22:49
浏览 205
已采纳

Gob解码器暂时抛出EOF错误然后停止

I'm trying to feed []byte over a chan to a gob decoder. It works, but at first the decoder throws a whole bunch of EOF errors then stops. When it stops throwing errors the program behaves exactly like I would expect with it decoding gobs and processing the structs it produces correctly.

This is the calling function, the channel that is being read from is an SSH channel.

log.Println("Reading channel")
dchan := make(chan []byte, 200)
go decoder(dchan)
for {
    buf := make([]byte, 1024)
    //log.Println("Waiting for data")
    numBytes, err := channel.Read(buf)
    if err != nil {
        log.Println(err)
        continue
    }
    dchan <- buf[:numBytes]
}

The decoder function looks like this:

func decoder(dchan chan []byte) error {
  gob.Register(datums.Message{})
  var message datums.Message
  bbuf := bytes.NewBuffer(make([]byte, 512))
  dec := gob.NewDecoder(bbuf)
  for data := range dchan {
    //log.Println("Decoding data")
    bbuf.Write(data)
    err := dec.Decode(&message)
    if err != nil {
        log.Println("Error in decoder")
        log.Println(err)
        continue
    }
    //log.Println(&message)
  }
  return nil
}

I'm not sure if this is even a real issue, does the gob decoder remove the data from the buffer or does it leave it there until sufficient data shows up to generate a value?

  • 写回答

1条回答 默认 最新

  • duankeye2342 2019-03-17 00:14
    关注

    The call to channel.Read(buf) can read a partial gob. The decoder will return an error when attempting to decode the partial gob.

    Because the channel satisfies the io.Reader interface, the application can create the decoder directly on the channel:

    gob.Register(datums.Message{})
    dec := gob.NewDecoder(channel)
    for {
      var message datums.Message
      err := dec.Decode(&message)
      if err != nil {
         log.Println("Error in decoder", err)
         break
      }
      log.Println(&message)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决