登录
首页 >  Golang >  Go问答

Go 服务器接收端处理 TCP Protobuf 消息的一致性问题

来源:stackoverflow

时间:2024-02-22 15:36:23 408浏览 收藏

知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个Golang开发实战,手把手教大家学习《Go 服务器接收端处理 TCP Protobuf 消息的一致性问题》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!

问题内容

我有一个“代理”,它将二进制文件解析到缓冲区中,每当该缓冲区被填满时,就会通过 protobuf 消息将其发送到服务器,然后继续进行下一个二进制解析块,然后再次发送,等等

在服务器上,我使用简单的 net/conn 包来侦听代理连接并在 while-for 循环中将其读取到缓冲区中。 当代理端解析完成后,它会在 protobuf 消息中发送 terminate bool,表示这是最后一条消息,服务器可以继续处理收到的完整数据。

但是,如果我将调试打印留在发送方,则效果很好,从而使终端打印显着减慢通过 connection.write() 发送后续 protobuf 消息的时间间隔。

如果我取消注释此记录器,则它发送消息的速度太快,并且服务器第一个处理的传入消息是包含 terminate 标志的一个数据包,例如,它没有收到实际的有效负载,但立即收到最后一条消息。

我知道 tcp 并没有真正区分不同的 []byte 数据包,这很可能是导致此行为的原因。有没有更好的方法或替代方案?

代理端伪代码:

buffer := make([]byte, 1024)
    for {
        n, ioerr := reader.read(buffer)
        if ioerr == io.eof {
            ispayloadfinal = true

            // create protobuf message
            terminalmessage, err := createmessage_filepackage(
                2234,
                protobuf.messagetype_package,
                make([]byte, 1),
                ispayloadfinal,
            )
            // send terminate message
            sendprotobufmessage(connection, terminalmessage)
            break
        }
        // create regular protobuf message
        message, err := createmessage_filepackage(
            2234,
            protobuf.messagetype_package,
            (buffer)[:n],
            ispayloadfinal)
        sendprotobufmessage(connection, message)
   }

服务器端伪代码:

buffer := make([]byte, 2048)
    //var protomessage protobufmessage

    for artifactreceived != true {
        connection.setreaddeadline(time.now().add(timeoutduration))
        n, _ := connection.read(buffer)
        decodedmessage := &protobuf.filemessage{}
        if err := proto.unmarshal(buffer[:n], decodedmessage); err != nil {
            log.err(err).msg("error during unmarshalling")
        }

        if ispackagefinal := decodedmessage.getisterminated(); ispackagefinal == true {
            artifactreceived = true
            log.info().msg("artifact fully received")
            /* do stuff here */
            break
        }
        // handle partially arrived bytestream
        handleprotopackage(packagemessage, artifactpath)
        } else {
            fmt.println("invalid protobuf message")
        }
    }

以及供参考的原型文件:

message FilePackage{
    int32 id = 1;
    MessageType msgType = 2;
    bytes payload = 3;
    bool isTerminated = 4;

}

解决方案


正如您所说,最可能的原因似乎是“TCP 并没有真正区分不同的[]字节数据包”(TCP 流没有消息边界)。当您调用 connection.Read(buffer) (我假设 connectionnet.Conn)时,它将阻塞,直到某些数据可用(或达到读取截止时间),然后返回该数据(最多为缓冲区大小)。返回的数据可能是一条消息(正如您在测试中所看到的),但也可能是部分消息,或多条消息(时间和网络堆栈相关;您不应做出任何假设)。

protobuf docs 提供了建议的技术:

如果您采用这种方法,那么您可以在接收数据时使用 io.ReadFull (因为您将知道该大小需要多少字节,然后使用它来接收数据包)。

今天关于《Go 服务器接收端处理 TCP Protobuf 消息的一致性问题》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>