Protobuf-net中的OverFlowException和EndOfStreamException

时间:2012-11-20 08:48:38

标签: c# protocol-buffers protobuf-net

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

总的来说,它完美无缺。但我遇到了一些问题。

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

.proto unders:

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。

怎样才能解决这个问题?提前谢谢!

1 个答案:

答案 0 :(得分:2)

这令我担心:

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

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

  1. 完全以原始二进制形式交换; 无文字
  2. 使用类似base-64的东西,它可以安全地将任意二进制编码为ASCII