当前位置: > > > > 尝试使用 gob.Decoder() 解码 blob 时出现错误(gob:未知类型 ID 或损坏的数据)
来源:stackoverflow
2024-04-26 23:33:35
0浏览
收藏
一分耕耘,一分收获!既然打开了这篇文章《尝试使用 gob.Decoder() 解码 blob 时出现错误(gob:未知类型 ID 或损坏的数据)》,就坚持看下去吧!文中内容包含等等知识点…希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!
问题内容
我正在尝试将编码的 blob 发送到本地对等点列表(在本地计算机上的多个端口侦听的客户端代码),当我对某些对等点解码 blob 时,它可以工作,但对某些对等点来说没有并显示错误(gob:未知类型 id 或损坏的数据),我该如何解决这个问题?
//My blob struct type packet struct { Nodes []a1.Node Ledger *a1.Block ActionType string } //Encoding Part for i:=1; i<len(ConnectedNodes);i++{ var blob packet blob.Ledger = Ledger blob.ActionType = "AddBlock" blob.Nodes = []a1.Node{} conn, err := net.Dial("tcp", "localhost"+":"+ConnectedNodes[i].Port) if err != nil { // handle error fmt.Println("Error At Client In Making A Connection (sending New Block to client "+ ConnectedNodes[i].Name +")") } //sending request type to client _, _ = conn.Write([]byte("newblock add ")) //sending data to the client node //gob.Register(blob) encoder := gob.NewEncoder(conn) error := encoder.Encode(blob) if error != nil { log.Fatal(error) } } //Decoding Part running on another peer //adds new block to the Ledger //Recieving incoming data recvdSlice := make([]byte, 256) conn.Read(recvdSlice) RecievedData := string(recvdSlice) finalData := strings.Split(RecievedData, " ") if finalData[0] == "newblock"{ var blob packet decoder := gob.NewDecoder(conn) err := decoder.Decode(&blob) if err != nil { fmt.Println("error at decoding New Block on client!") fmt.Println(err) } fmt.Println(Ledger.Hash) fmt.Println(blob.Ledger.Hash) if(bytes.Compare(Ledger.Hash, blob.Ledger.Hash)) == 0 { fmt.Println("Ledger is already updated !") }else{ fmt.Println("New Block Added !") Ledger = blob.Ledger } a1.ListBlocks(Ledger) //SendingNewBlockToConnectedNodes() }
解决方案
发送方在编码gob之前写入13个字节(“newblock add”
)。
如果接收器在解码 gob 之前没有读取这 13 个字节,那么解码器将与数据流不同步并报告错误。
当数据可用、切片已满或读取连接时出错时,连接读取方法将返回。忽略错误,对连接上的 read 的调用将从连接中读取 1 到 len(recvdslice) 个字节。虽然不能保证读取到13字节的数据,但由于时序原因,实际中这种情况经常发生。
通过在解码 gob 之前仅读取前缀来修复。一种方法是用换行符分隔前缀。
将发件人代码更改为:
_, _ = conn.write([]byte("newblock add \n"))
将接收者代码更改为:
br := bufio.newreader(conn) receiveddata, err := br.readstring('\n') if err != nil { // handle error } finaldata := strings.split(receiveddata, " ") if finaldata[0] == "newblock"{ var blob packet decoder := gob.newdecoder(br) // <-- decode from the buffered reader err := decoder.decode(&blob)
另一个修复是使用 gob 编解码器作为前缀。将发件人更改为:
encoder := gob.newencoder(conn) if err := encoder.encode("newblock add "); err != nil { // handle error } if err := encoder.encode(blob); err != nil { // handle error }
将接收器更改为:
decoder := gob.NewDecoder(conn) var receivedData string if err := decoder.Decode(&receivedData); err != nil { // handle error } finalData := strings.Split(receivedData, " ") if finalData[0] == "newblock"{ var blob packet err := decoder.Decode(&blob)
理论要掌握,实操不能落!以上关于《尝试使用 gob.Decoder() 解码 blob 时出现错误(gob:未知类型 ID 或损坏的数据)》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注公众号吧!