1

我一直在阅读有关 protobuf-net 的内容,这太棒了!

一般来说,它工作得很好。但是我遇到了一些问题。

我正在尝试使用 protobuf 在 Python 和 C# 之间编写通信代码。

.proto 如下:

message GetAllCalculate{
    required string agentID=1;
}

message CalculateInfo{
    required string CalStarttime=1;
    optional string CalEndtime=2;
    required string Smiles=3;
    optional string CAS=4;
    optional string ChName=5;
    optional string EnName=6;
    required string Param=7;
    required string Result=8;
    required bool IsFinished=9;
}

message GetAllCalulateResponse{
    required bool  isSuccessful = 1;
    required int32 Count=2;
    repeated CalculateInfo History=3;

}

在 Python 客户端中,代码如下:

msg_resp = GetAllCalulateResponse()
  calculateInfo = [None] * 2
    cnt = 0
    for result in resultSets:   #resultSets can read from other place,like database
        calculateInfo[cnt] = msg_resp.History.add()
        calculateInfo[cnt].CalStarttime = str(result.calculateStartTime)
        calculateInfo[cnt].CalEndtime = result.calculateEndTime.strftime('%Y-%m-%d %X')
        calculateInfo[cnt].IsFinished = result.isFinished
        calculateInfo[cnt].Param = result.paramInfo
        **calculateInfo[cnt].Result = str('ff'*50) #result.result**

        calculateInfo[cnt].Smiles = result.smilesInfo.smilesInfo
        calculateInfo[cnt].CAS = result.smilesInfo.casInfo


        nameSets = CompoundName.objects.filter(simlesInfo=result.smilesInfo.pk,isDefault=True)
        for nameSet in nameSets:
            if nameSet.languageID.languageStr == Chinese_Name_Label:
                calculateInfo[cnt].ChName = nameSet.nameStr 
            elif nameSet.languageID.languageStr == English_Name_Label:
                calculateInfo[cnt].EnName = nameSet.nameStr

        cnt = cnt +1 

C# 代码(使用 Protobuf-net):

string retString = HTTPPost2UTF8(bytes, GetAllCalculateHandlerAPI); //Get from Python Clint
bytesOut = System.Text.Encoding.UTF8.GetBytes(retString);
MemoryStream streamOut = new MemoryStream(bytesOut);
GetAllCalulateResponse response = Serializer.Deserialize <GetAllCalulateResponse>(streamOut);

但是当我**calculateInfo[cnt].Result = str('ff'*50) #result.result**做大时,比如 str('ff') * 5000,C# 客户端会抛出 OverFlowException。当我设置它 str('ff') * 100 时,它会抛出 EndOfStreamException。

如何解决这个问题?提前致谢!

4

1 回答 1

2

这让我很担心:

string retString = HTTPPost2UTF8(bytes, GetAllCalculateHandlerAPI); //Get from Python
bytesOut = System.Text.Encoding.UTF8.GetBytes(retString);
MemoryStream streamOut = new MemoryStream(bytesOut);

protobuf 数据不是 text,而且肯定不是 UTF8。没有有效的方法可以将 protobuf 二进制文件作为 UTF8 传递而不破坏它。选项:

  1. 将其完全交换为原始二进制文件;没有文字
  2. 使用 base-64 之类的东西,它可以安全地将任意二进制编码为 ASCII
于 2012-11-20T21:35:07.227 回答