尝试使用 gob.Decoder() 解码 blob 时出现错误

我试图将编码的 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()

    }


猛跑小猪
浏览 122回答 1
1回答

UYOU

发送方在编码 gob ( "newblock add ") 之前写入 13 个字节。如果接收器在解码 gob 之前没有读取这 13 个字节,则解码器将与数据流不同步并报告错误。当数据可用、切片已满或读取连接时出错时,连接 Read 方法将返回。忽略错误,对连接上的 Read 的调用将从连接中读取 1 到 len(recvdSlice) 个字节。虽然不能保证读取到 13 字节的数据,但由于时序原因,实际中这种情况经常发生。通过在解码 gob 之前仅读取前缀来修复。一种方法是用换行符分隔前缀。将发件人代码更改为:&nbsp;_, _ = conn.Write([]byte("newblock add \n"))将接收者代码更改为:&nbsp;br := bufio.NewReader(conn)&nbsp;receivedData, err := br.ReadString('\n')&nbsp;if err != nil {&nbsp; &nbsp; &nbsp;// handle error&nbsp;}&nbsp;finalData := strings.Split(receivedData, " ")&nbsp;if finalData[0] == "newblock"{&nbsp; &nbsp; var blob packet&nbsp; &nbsp; decoder := gob.NewDecoder(br) // <-- decode from the buffered reader&nbsp; &nbsp; err := decoder.Decode(&blob)另一个修复方法是使用 gob 编解码器作为前缀。将发件人更改为:&nbsp; &nbsp; encoder := gob.NewEncoder(conn)&nbsp; &nbsp; if err := encoder.Encode("newblock add "); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; // handle error&nbsp; &nbsp; }&nbsp; &nbsp; if err := encoder.Encode(blob); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; // handle error&nbsp; &nbsp; }将接收器更改为:decoder := gob.NewDecoder(conn)var receivedData stringif err := decoder.Decode(&receivedData); err != nil {&nbsp; &nbsp; &nbsp;// handle error}finalData := strings.Split(receivedData, " ")if finalData[0] == "newblock"{&nbsp; &nbsp; var blob packet&nbsp; &nbsp; err := decoder.Decode(&blob)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go