protected override object DecodeMsg(string protoName, byte[] bytes, int offset, int count) { var tmp = new byte[count]; Array.Copy(bytes, offset, tmp, 0, count); var istream = new CodedInputStream(tmp); var msg = Activator.CreateInstance(Type.GetType(protoName)) as IMessage; istream.ReadMessage(msg); return(msg); }
/// <summary> /// Adds entries to the map from the given stream. /// </summary> /// <remarks> /// It is assumed that the stream is initially positioned after the tag specified by the codec. /// This method will continue reading entries from the stream until the end is reached, or /// a different tag is encountered. /// </remarks> /// <param name="input">Stream to read from</param> /// <param name="codec">Codec describing how the key/value pairs are encoded</param> public void AddEntriesFrom(CodedInputStream input, Codec codec) { var adapter = new Codec.MessageAdapter(codec); do { adapter.Reset(); input.ReadMessage(adapter); this[adapter.Key] = adapter.Value; } while (input.MaybeConsumeTag(codec.MapTag)); }
private Task <InvocationDescriptor> CreateInvocationDescriptorInt(Stream stream, Func <string, Type[]> getParams) { var inputStream = new CodedInputStream(stream, leaveOpen: true); var invocationHeader = new RpcInvocationHeader(); inputStream.ReadMessage(invocationHeader); var argumentTypes = getParams(invocationHeader.Name); var invocationDescriptor = new InvocationDescriptor(); invocationDescriptor.Method = invocationHeader.Name; invocationDescriptor.Id = invocationHeader.Id.ToString(); invocationDescriptor.Arguments = new object[argumentTypes.Length]; var primitiveParser = PrimitiveValue.Parser; for (var i = 0; i < argumentTypes.Length; i++) { if (typeof(int) == argumentTypes[i]) { var value = new PrimitiveValue(); inputStream.ReadMessage(value); invocationDescriptor.Arguments[i] = value.Int32Value; } else if (typeof(string) == argumentTypes[i]) { var value = new PrimitiveValue(); inputStream.ReadMessage(value); invocationDescriptor.Arguments[i] = value.StringValue; } else { var serializer = _serviceProvider.GetRequiredService <ProtobufSerializer>(); invocationDescriptor.Arguments[i] = serializer.GetValue(inputStream, argumentTypes[i]); } } return(Task.FromResult(invocationDescriptor)); }
public Task <SocialWeather.WeatherReport> ReadAsync(Stream stream) { var inputStream = new CodedInputStream(stream, leaveOpen: true); var protoWeatherReport = new Protobuf.WeatherReport(); inputStream.ReadMessage(protoWeatherReport); return(Task.FromResult(new SocialWeather.WeatherReport { Temperature = protoWeatherReport.Temperature, ReportTime = protoWeatherReport.ReportTime, Weather = (Weather)(int)protoWeatherReport.Weather, ZipCode = protoWeatherReport.ZipCode })); }
public object GetValue(CodedInputStream inputStream, Type type) { if (type == typeof(Person)) { var value = new PersonMessage(); inputStream.ReadMessage(value); return(new Person { Name = value.Name, Age = value.Age }); } throw new InvalidOperationException("(Deserialize) Unknown type."); }
/// <summary> /// 反序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <param name="data"></param> public void DeSerialize <T>(T t, byte[] data) where T : IMessage { try { using (MemoryStream stream = new MemoryStream(data)) { CodedInputStream inputStream = new CodedInputStream(data); inputStream.ReadMessage(t); } } catch (Exception e) { Console.WriteLine(e); } }
public Dictionary <Type, object> ReadParam() { Dictionary <Type, object> pairs = new Dictionary <Type, object>(); foreach (var item in Params) { object o = null; Type t = Type.GetType(item.Name); if (t != null) { CodedInputStream cis = new CodedInputStream(item.Data.ToByteArray()); if (t == typeof(int)) { o = cis.ReadInt32(); } else if (t == typeof(long)) { o = cis.ReadInt64(); } else if (t == typeof(float)) { o = cis.ReadFloat(); } else if (t == typeof(double)) { o = cis.ReadDouble(); } else if (t == typeof(bool)) { o = cis.ReadBool(); } else if (t == typeof(string)) { o = cis.ReadString(); } else if (typeof(IMessage).IsAssignableFrom(t)) { o = Activator.CreateInstance(t); cis.ReadMessage((IMessage)o); } pairs.Add(t, o); } } return(pairs); }
internal ByteString Invoke(Request request) { var outStream = new CodedOutputStream(rpcClient.GetStream()); outStream.WriteLength(request.CalculateSize()); request.WriteTo(outStream); outStream.Flush(); var inStream = new CodedInputStream(rpcClient.GetStream()); var response = new Response(); inStream.ReadMessage(response); if (response.HasError) { throw new RPCException(response.Error); } return(response.HasReturnValue ? response.ReturnValue : null); }
public void MergeFrom(CodedInputStream input) { uint num; while ((num = input.ReadTag()) != 0) { if (num != 10) { _unknownFields = UnknownFieldSet.MergeFieldFrom(_unknownFields, input); continue; } if (info_ == null) { info_ = new DeckInfo(); } input.ReadMessage(info_); } }
// 反序列化protobuf public static T Deserialize <T>(byte[] dataBytes) where T : IMessage, new() { CodedInputStream stream = new CodedInputStream(dataBytes); T msg = new T(); try { stream.ReadMessage(msg); } catch (System.Exception e) { Console.WriteLine("接收错误:" + e.ToString()); //发过来的是utf8-string string str = System.Text.Encoding.UTF8.GetString(dataBytes); Console.WriteLine(str); } return(msg); }
public void MergeFrom(CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch (tag) { default: _unknownFields = UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (signatureInfo_ == null) { SignatureInfo = new SignatureInfo(); } input.ReadMessage(SignatureInfo); break; } case 16: { BatchNum = input.ReadInt32(); break; } case 24: { BatchSize = input.ReadInt32(); break; } case 34: { Signature = input.ReadBytes(); break; } } } }
private static OrcaAdv Load(uint adv_id) { string filename = string.Format("{0}/{1}.dat", _file_root_path, adv_id); if (!File.Exists(filename)) { return(null); } FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read); CodedInputStream input = new CodedInputStream(fs, true); OrcaAdv adv = new OrcaAdv { AdvId = adv_id }; input.ReadMessage(adv); fs.Close(); return(adv); }
public async override void ReadHandler(byte[] data, int receivedLength) { if (!IsOpen()) { return; } var stream = new CodedInputStream(data, 0, receivedLength); while (!stream.IsAtEnd) { var header = new Header(); stream.ReadMessage(header); if (header.ServiceId != 0xFE && header.ServiceHash != 0) { var handler = Global.LoginServiceMgr.GetHandler(header.ServiceHash, header.MethodId); if (handler != null) { handler.Invoke(this, header.Token, stream); } else { Log.outError(LogFilter.ServiceProtobuf, $"{GetClientInfo()} tried to call not implemented methodId: {header.MethodId} for servicehash: {header.ServiceHash}"); SendResponse(header.Token, BattlenetRpcErrorCode.RpcNotImplemented); } } else { var handler = responseCallbacks.LookupByKey(header.Token); if (handler != null) { handler(stream); responseCallbacks.Remove(header.Token); } } } await AsyncRead(); }
public void MergeFrom(CodedInputStream input) { uint num; while ((num = input.ReadTag()) != 0) { switch (num) { default: _unknownFields = UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10u: if (spell_ == null) { spell_ = new SpellInfo(); } input.ReadMessage(spell_); break; case 16u: from_ = (SpellMovementZone)input.ReadEnum(); break; case 24u: to_ = (SpellMovementZone)input.ReadEnum(); break; case 34u: { bool?flag = _single_discardedBecauseHandWasFull_codec.Read(input); if (!discardedBecauseHandWasFull_.HasValue || flag != false) { DiscardedBecauseHandWasFull = flag; } break; } } } }
public void MergeFrom(CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch (tag) { default: _unknownFields = UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (signatureInfo_ == null) { SignatureInfo = new global::NL.Rijksoverheid.ExposureNotification.BackEnd.GeneratedGaenFormat.SignatureInfo(); } input.ReadMessage(SignatureInfo); break; } case 16: { BatchNum = input.ReadInt32(); break; } case 24: { BatchSize = input.ReadInt32(); break; } case 34: { Signature = input.ReadBytes(); break; } } } }
public MessageToClient?ReadOne() { beginRead: if (Finished) { return(null); } var pos = cos.Position; try { MessageToClient?msg = new MessageToClient(); cos.ReadMessage(msg); return(msg); } catch (InvalidProtocolBufferException) { var leftByte = buffer.Length - pos; // 上次读取剩余的字节 for (int i = 0; i < leftByte; ++i) { buffer[i] = buffer[pos + i]; } var bufferSize = gzs.Read(buffer, (int)leftByte, (int)(buffer.Length - leftByte)) + leftByte; if (bufferSize == leftByte) { Finished = true; return(null); } if (bufferSize != buffer.Length) // 不留空位,防止 CodedInputStream 获取信息错误 { var tmpBuffer = new byte[bufferSize]; Array.Copy(buffer, tmpBuffer, bufferSize); buffer = tmpBuffer; } cos = new CodedInputStream(buffer); goto beginRead; } }
void TestProtoSimple() { var msg = new MsgMove(); msg.X = 4; msg.Y = -7; msg.Z = -4; byte[] bytes; using (var ms = new MemoryStream()) { var ostream = new CodedOutputStream(ms); ostream.WriteMessage(msg as IMessage); ostream.Flush(); bytes = ms.ToArray(); } var istream = new CodedInputStream(bytes); var msg2 = System.Activator.CreateInstance(typeof(MsgMove)) as IMessage; istream.ReadMessage(msg2); Debug.LogFormat("msg:{0},msg2:{1}", msg, msg2); }
public void MergeFrom(CodedInputStream input) { uint num; while ((num = input.ReadTag()) != 0) { switch (num) { default: _unknownFields = UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8u: eventType_ = (Types.EventType)input.ReadEnum(); break; case 16u: EventId = input.ReadSInt32(); break; case 26u: { int?num6 = _single_parentEventId_codec.Read(input); if (!parentEventId_.HasValue || num6 != 0) { ParentEventId = num6; } break; } case 32u: Int1 = input.ReadInt32(); break; case 40u: Int2 = input.ReadInt32(); break; case 48u: Int3 = input.ReadInt32(); break; case 56u: Int4 = input.ReadInt32(); break; case 64u: Int5 = input.ReadInt32(); break; case 72u: Int6 = input.ReadInt32(); break; case 80u: Int7 = input.ReadInt32(); break; case 90u: String1 = input.ReadString(); break; case 96u: Bool1 = input.ReadBool(); break; case 106u: if (cellCoord1_ == null) { cellCoord1_ = new CellCoord(); } input.ReadMessage(cellCoord1_); break; case 114u: if (cellCoord2_ == null) { cellCoord2_ = new CellCoord(); } input.ReadMessage(cellCoord2_); break; case 120u: companionReserveState1_ = (CompanionReserveState)input.ReadEnum(); break; case 128u: companionReserveState2_ = (CompanionReserveState)input.ReadEnum(); break; case 136u: damageReductionType1_ = (DamageReductionType)input.ReadEnum(); break; case 144u: fightResult1_ = (FightResult)input.ReadEnum(); break; case 154u: if (gameStatistics1_ == null) { gameStatistics1_ = new GameStatistics(); } input.ReadMessage(gameStatistics1_); break; case 160u: teamsScoreModificationReason1_ = (TeamsScoreModificationReason)input.ReadEnum(); break; case 170u: { int?num5 = _single_optInt1_codec.Read(input); if (!optInt1_.HasValue || num5 != 0) { OptInt1 = num5; } break; } case 178u: { int?num4 = _single_optInt2_codec.Read(input); if (!optInt2_.HasValue || num4 != 0) { OptInt2 = num4; } break; } case 186u: { int?num3 = _single_optInt3_codec.Read(input); if (!optInt3_.HasValue || num3 != 0) { OptInt3 = num3; } break; } case 194u: { int?num2 = _single_optInt4_codec.Read(input); if (!optInt4_.HasValue || num2 != 0) { OptInt4 = num2; } break; } case 202u: cellCoordList1_.AddEntriesFrom(input, _repeated_cellCoordList1_codec); break; case 210u: spellMovementList1_.AddEntriesFrom(input, _repeated_spellMovementList1_codec); break; case 218u: castTargetList1_.AddEntriesFrom(input, _repeated_castTargetList1_codec); break; case 224u: case 226u: intList1_.AddEntriesFrom(input, _repeated_intList1_codec); break; case 232u: case 234u: intList2_.AddEntriesFrom(input, _repeated_intList2_codec); break; } } }
public void WriteTo_Message() { var message1 = new ForeignMessage { C = 20 }; var message2 = new ForeignMessage { C = 25 }; uint tag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited); var field = new RepeatedField<ForeignMessage> { message1, message2 }; var stream = new MemoryStream(); var output = new CodedOutputStream(stream); field.WriteTo(output, FieldCodec.ForMessage(tag, ForeignMessage.Parser)); output.Flush(); stream.Position = 0; var input = new CodedInputStream(stream); input.AssertNextTag(tag); Assert.AreEqual(message1, input.ReadMessage(ForeignMessage.Parser)); input.AssertNextTag(tag); Assert.AreEqual(message2, input.ReadMessage(ForeignMessage.Parser)); Assert.IsTrue(input.IsAtEnd); }
private static void TrySerial(bool run = false) { if (!run) { return; } using var serial = new SerialPort { PortName = "COM4", BaudRate = 115200, Parity = Parity.None, DataBits = 7, StopBits = StopBits.One, DtrEnable = true }; var sensors = new Sensors { List = { new Sensor { Analog = new AnalogSensor { UpperRange = 1023, LowerRange = 0 }, MeasurementUnit = "B47", //Kilonewton Pin = 20 }, new Sensor { Digital = new DigitalSensor(), MeasurementUnit = "1N", Pin = 10 } } }; try { serial.Open(); } catch (Exception e) { Console.WriteLine(e); return; } using var file = System.IO.File.CreateText("D:\\Users\\pdimp\\Pictures\\output.txt"); using var codedInputStream = new CodedInputStream(serial.BaseStream); var s = new Stopwatch(); serial.DataReceived += (sender, eventArgs) => { s.Reset(); s.Start(); var ss = new Sensors(); codedInputStream.ReadMessage(ss); s.Stop(); Console.WriteLine($"pc time after parsing: {s.Elapsed.TotalMilliseconds} ms"); Console.WriteLine($"timestamp: {ss.Timestamp}"); //foreach (var s in ss.List) // switch (s.TypeCase) // { // case Sensor.TypeOneofCase.Analog: // file.WriteLine($"analog: {s.Analog.Value} {s.MeasurementUnit}"); // break; // case Sensor.TypeOneofCase.Digital: // file.WriteLine($"digital: {s.Digital.Value} {s.MeasurementUnit}, time of change: {s.Digital.Timestamp}"); // break; // default: // file.WriteLine("Sensor type is unknown"); // break; // } }; serial.Write(sensors.ToByteArray(), 0, sensors.CalculateSize()); Console.ReadKey(); serial.Close(); Console.ReadKey(); }
public void MergeFrom(CodedInputStream input) { uint num; while ((num = input.ReadTag()) != 0) { switch (num) { default: _unknownFields = UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8u: EntityId = input.ReadInt32(); break; case 16u: EntityType = input.ReadInt32(); break; case 26u: { string text2 = _single_name_codec.Read(input); if (name_ == null || text2 != "") { Name = text2; } break; } case 34u: { int?num6 = _single_defId_codec.Read(input); if (!defId_.HasValue || num6 != 0) { DefId = num6; } break; } case 42u: { int?num5 = _single_weaponId_codec.Read(input); if (!weaponId_.HasValue || num5 != 0) { WeaponId = num5; } break; } case 50u: { int?num9 = _single_genderId_codec.Read(input); if (!genderId_.HasValue || num9 != 0) { GenderId = num9; } break; } case 58u: { int?num7 = _single_playerIndexInFight_codec.Read(input); if (!playerIndexInFight_.HasValue || num7 != 0) { PlayerIndexInFight = num7; } break; } case 66u: { int?num3 = _single_ownerId_codec.Read(input); if (!ownerId_.HasValue || num3 != 0) { OwnerId = num3; } break; } case 74u: { int?num2 = _single_teamId_codec.Read(input); if (!teamId_.HasValue || num2 != 0) { TeamId = num2; } break; } case 82u: { int?num8 = _single_level_codec.Read(input); if (!level_.HasValue || num8 != 0) { Level = num8; } break; } case 88u: case 90u: properties_.AddEntriesFrom(input, _repeated_properties_codec); break; case 98u: if (position_ == null) { position_ = new CellCoord(); } input.ReadMessage(position_); break; case 106u: { int?num4 = _single_direction_codec.Read(input); if (!direction_.HasValue || num4 != 0) { Direction = num4; } break; } case 114u: caracs_.AddEntriesFrom(input, _map_caracs_codec); break; case 122u: { string text = _single_customSkin_codec.Read(input); if (customSkin_ == null || text != "") { CustomSkin = text; } break; } case 130u: { bool?flag = _single_actionDoneThisTurn_codec.Read(input); if (!actionDoneThisTurn_.HasValue || flag != false) { ActionDoneThisTurn = flag; } break; } } } }
/// <exception cref="Com.Google.Protobuf.InvalidProtocolBufferException"/> private ConcatVectorTable(CodedInputStream input, ExtensionRegistryLite extensionRegistry) { InitFields(); int mutable_bitField0_ = 0; UnknownFieldSet.Builder unknownFields = UnknownFieldSet.NewBuilder(); try { bool done = false; while (!done) { int tag = input.ReadTag(); switch (tag) { case 0: { done = true; break; } default: { if (!ParseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { if (!((mutable_bitField0_ & unchecked ((int)(0x00000001))) == unchecked ((int)(0x00000001)))) { dimensionSize_ = new List <int>(); mutable_bitField0_ |= unchecked ((int)(0x00000001)); } dimensionSize_.Add(input.ReadInt32()); break; } case 10: { int length = input.ReadRawVarint32(); int limit = input.PushLimit(length); if (!((mutable_bitField0_ & unchecked ((int)(0x00000001))) == unchecked ((int)(0x00000001))) && input.GetBytesUntilLimit() > 0) { dimensionSize_ = new List <int>(); mutable_bitField0_ |= unchecked ((int)(0x00000001)); } while (input.GetBytesUntilLimit() > 0) { dimensionSize_.Add(input.ReadInt32()); } input.PopLimit(limit); break; } case 18: { if (!((mutable_bitField0_ & unchecked ((int)(0x00000002))) == unchecked ((int)(0x00000002)))) { factorTable_ = new List <ConcatVectorProto.ConcatVector>(); mutable_bitField0_ |= unchecked ((int)(0x00000002)); } factorTable_.Add(input.ReadMessage(ConcatVectorProto.ConcatVector.Parser, extensionRegistry)); break; } } } } catch (InvalidProtocolBufferException e) { throw e.SetUnfinishedMessage(this); } catch (IOException e) { throw new InvalidProtocolBufferException(e.Message).SetUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & unchecked ((int)(0x00000001))) == unchecked ((int)(0x00000001)))) { dimensionSize_ = Java.Util.Collections.UnmodifiableList(dimensionSize_); } if (((mutable_bitField0_ & unchecked ((int)(0x00000002))) == unchecked ((int)(0x00000002)))) { factorTable_ = Java.Util.Collections.UnmodifiableList(factorTable_); } this.unknownFields = unknownFields.Build(); MakeExtensionsImmutable(); } }
public void MergeFrom(CodedInputStream input) { uint num; while ((num = input.ReadTag()) != 0) { switch (num) { default: _unknownFields = UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8u: Id = input.ReadInt32(); break; case 16u: GiveAllCompanions = input.ReadBool(); break; case 24u: GiveAllWeapons = input.ReadBool(); break; case 34u: { Types.SetLevel setLevel = new Types.SetLevel(); if (cmdCase_ == CmdOneofCase.SetWeaponLevel) { setLevel.MergeFrom(SetWeaponLevel); } input.ReadMessage(setLevel); SetWeaponLevel = setLevel; break; } case 42u: { Types.SetAllLevels setAllLevels = new Types.SetAllLevels(); if (cmdCase_ == CmdOneofCase.SetAllWeaponLevels) { setAllLevels.MergeFrom(SetAllWeaponLevels); } input.ReadMessage(setAllLevels); SetAllWeaponLevels = setAllLevels; break; } case 50u: { Types.SetGender setGender = new Types.SetGender(); if (cmdCase_ == CmdOneofCase.SetGender) { setGender.MergeFrom(SetGender); } input.ReadMessage(setGender); SetGender = setGender; break; } } } }
public IMessage ReadMessage(IBuilder builder) { m_stream.ReadMessage(builder, ExtensionRegistry.Empty); return(builder.WeakBuild()); }
IMessage ReadMessage(CodedInputStream reader, IBuilder builder) { reader.ReadMessage(builder, ExtensionRegistry.Empty); return(builder.WeakBuildPartial()); }