protected override void Test(FTestMessage message, Action <FTestMessage> customAssert = null) { var serialized = ProtoSerializer.Serialize(message); var deserialized = ProtoSerializer.Deserialize <FTestMessage>(serialized); AssertDeserialized(message, deserialized, customAssert); }
void LoadAllGuidPlayers() { playerList = new List <PlayerData>(); string[] dirs = Directory.GetDirectories(pathData, "", SearchOption.TopDirectoryOnly); string playerFileName = DataType.Player.ToString() + dataFileExt; byte[] buffer; FileHelper fileHelper = SingletonObject.getInstance <FileHelper>(); for (int i = 0, max = dirs.Length; i < max; ++i) { string filePlayer = Path.Combine(pathData, string.Format("{0}/{1}", dirs[i], playerFileName)); if (File.Exists(filePlayer)) { buffer = fileHelper.ReadFile(filePlayer); PlayerData player = ProtoSerializer.ProtoDeSerialize <PlayerData>(buffer); if (null != player) { playerList.Add(player); } } } if (playerList.Count > 1) { playerList.Sort((left, right) => { return((int)(left.lastLogin - right.lastLogin)); }); } if (playerList.Count > 0) { curPlayer = playerList[playerList.Count - 1]; } }
public static string SerliazeRootTask(BehaviorManager.BehaviorTree behaviorTree) { string serializationFilePath = ""; if (null == behaviorTree) { #if UNITY_EDITOR Debug.LogWarning("RootTaskSerializer.SerliazeRootTask ERROR : behaviorTree is NULL"); #endif return(serializationFilePath); } string behaviorTreeName = BehaviorTreeUtility.GetClassNameFromInstance(behaviorTree); string rootTaskName = BehaviorTreeUtility.GetClassNameFromInstance(behaviorTree.rootTask); // 将行为树-根结点键值对存进map BehaviorTreeNamewithRootTaskNameMap.AddPairValue(behaviorTreeName, rootTaskName); // 将map刷新到外存 BTNameAndRTNameDic instance = new BTNameAndRTNameDic(); instance.BTNamRTNameDic = BehaviorTreeNamewithRootTaskNameMap.BTNameMapRTNameDic; ProtoSerializer.SerializeToFile(instance, ProtoSerializer.CONFIG_FILE_NAME); // TODO: 其实序列化的时候不需要泛型,只有反序列化才需要知道 serializationFilePath = ProtoSerializer.SerializeToFile(behaviorTree.rootTask, behaviorTreeName); return(serializationFilePath); }
private void SaveSettings() { try { var brokerAccount = DataManager.Broker.ActiveAccounts.FirstOrDefault(p => p.IsDefault); if (brokerAccount != null) { Settings.DefaultBrokerAccount = brokerAccount.UserName; Settings.DefaultBrokerName = brokerAccount.BrokerName; } else { Settings.DefaultBrokerAccount = string.Empty; Settings.DefaultBrokerName = string.Empty; } Settings.AutoLoginBrokerAccounts = true; var data = ProtoSerializer.Serialize(Settings); File.WriteAllBytes(PathManager.SettingsFileName, data); } catch (Exception ex) { AppLogger.Error(ex, "Failed save settings"); } }
public byte[] Encode(Protobuf protobuf) { try { MemoryStream serializeStream = new MemoryStream(); ProtoSerializer.Serialize(protobuf.ProtoID, serializeStream, protobuf.Proto); // 整个数据流结构为 // 4个字节的包长度(不算在长度中), 2个字节的包长度, 2个字节的请求类型 MemoryStream sendStream = new MemoryStream(); sendStream.SetLength(serializeStream.Length + 8); sendStream.Position = 0; sendStream.Write(BitConverter.GetBytes((int)serializeStream.Length + 4), 0, 4); sendStream.Write(BitConverter.GetBytes((short)serializeStream.Length + 4), 0, 2); sendStream.Write(BitConverter.GetBytes((short)protobuf.ProtoID), 0, 2); sendStream.Write(serializeStream.GetBuffer(), 0, (int)serializeStream.Length); var res = new byte[sendStream.Length]; Array.Copy(sendStream.GetBuffer(), res, sendStream.Length); return(res); } catch (Exception ex) { UnityEngine.Debug.LogError("Encode protobuf fail!"); UnityEngine.Debug.LogException(ex); } return(null); }
/// <summary> /// 传入带命名空间的类名,反序列化出该类 /// </summary> /// <param name="behaviorName"></param> /// <param name="behaviorTree"></param> public static void Load(string behaviorName, ref BehaviorManager.BehaviorTree behaviorTree) { if (null == behaviorTree.rootTask) { // 读取BTName-RTName配置信息 string ConfigDicFilePath = ProtoSerializer.SERIALIZATION_CACHE_DATA_PATH + ProtoSerializer.CONFIG_FILE_NAME + ProtoSerializer.DATA_POSTFIX; BTNameAndRTNameDic instance = new BTNameAndRTNameDic(); ProtoSerializer.DeserializeFromFile(ConfigDicFilePath, typeof(BTNameAndRTNameDic), ref instance); BehaviorTreeNamewithRootTaskNameMap.BTNameMapRTNameDic = instance.BTNamRTNameDic; // 反序列化根结点 string filePath = ProtoSerializer.SERIALIZATION_CACHE_DATA_PATH + behaviorName + ProtoSerializer.DATA_POSTFIX; string rootTaskName = ""; if (BehaviorTreeNamewithRootTaskNameMap.BTNameMapRTNameDic.ContainsKey(behaviorName)) { rootTaskName = BehaviorTreeNamewithRootTaskNameMap.BTNameMapRTNameDic[behaviorName]; } Type type = Type.GetType(rootTaskName); ProtoSerializer.DeserializeFromFile(filePath, type, ref behaviorTree.rootTask); // 构建行为树结构 behaviorTree.InitalBTStructureData(behaviorTree.rootTask); } if (BehaviorManager.instance.isEnableLog) { LogChildren(behaviorTree.rootTask); } }
#pragma warning disable RCS1163, IDE0060 // Unused parameter. public static void Test <T>(T obj, ProtoSerializer <T> serializer, string message, byte[] expected) #pragma warning restore RCS1163, IDE0060 // Unused parameter. { byte[] data; using (MemoryStream ms = new MemoryStream()) { long reported; var state = ProtoWriter.State.Create(ms, RuntimeTypeModel.Default, null); try { serializer(ref state, obj); state.Close(); #pragma warning disable CS0618 reported = state.GetPosition(); #pragma warning restore CS0618 } finally { state.Dispose(); } data = ms.ToArray(); Assert.Equal(reported, data.Length); //, message + ":reported/actual"); } Assert.Equal(expected.Length, data.Length); //, message + ":Length"); for (int i = 0; i < data.Length; i++) { Assert.Equal(expected[i], data[i]); //, message + ":" + i); } }
/// <summary> /// Returns all of the Testmodels stored on the service. /// </summary> /// <returns></returns> public async Task <List <TestModel> > GetTestModelsAsync() { List <TestModel> returnModels = new List <TestModel>(); try { // Get the data HttpResponseMessage response = await _client.GetAsync(testAPI); // Deserialize the data if it was successful if (response.IsSuccessStatusCode) { byte[] data = await response.Content.ReadAsByteArrayAsync(); returnModels = ProtoSerializer .DeserializeCollection <TestModel>(data) .ToList(); } else { // Report if the service call was not successful throwCommunicationException(response.StatusCode); } } catch (Exception ex) { logError(ex, "retrieve the test models"); } return(returnModels); }
private async Task SendClosePacketAsync() { if (this.isEstablished == false) { throw new SessionNotEstablishedException(); } var packet = new Packet { IsClose = true }; var data = ProtoSerializer.Serialize(packet); var sendDataTasks = new Task[this.connections.Count]; var i = 0; foreach (var connection in this.connections.Values) { var sendDataTask = this.SendDataAsync(connection.LocalClientId, connection.RemoteClientId, data); sendDataTasks[i] = sendDataTask.ToTimeoutTask( connection.RetransmissionTimeout, new WriteDeadlineExceededException()); } await Task.WhenAny(sendDataTasks); }
static Global() { Serializer = new ProtoSerializer(); ExceptionHandler = new ExceptionHandler(); IdProvider = new SimpleIdProvider(); BufferManagerFactory = new BufferManagerFactory(); }
public bool Decode(byte[] data, out List <Protobuf> protobufs) { protobufs = new List <Protobuf>(); try { // 将新接收的数据写入stream尾 stream.Position = stream.Length; stream.Write(data, 0, data.Length); stream.Position = 0; // 4个字节协议长度 var sumLen = br.ReadInt32(); while (sumLen + 4 <= stream.Length) { // 2个字节协议号 stream.Position = 6; var protoID = br.ReadInt16(); // 协议反序列化 MemoryStream protoStream = new MemoryStream(); protoStream.Write(stream.ToArray(), 8, sumLen - 4); printProtoContent((ProtoNameIds)protoID, protoStream.GetBuffer(), sumLen - 4); // 将流位置重置为开头 protoStream.Position = 0; protobufs.Add(new Protobuf() { Proto = (IExtensible)ProtoSerializer.ParseFrom((ProtoNameIds)protoID, protoStream), ProtoID = (ProtoNameIds)protoID }); // 判断是否有粘包 stream.Position = sumLen + 4; if (stream.Length - stream.Position > 0) { MemoryStream newStream = new MemoryStream(); newStream.Write(stream.ToArray(), (int)stream.Position, (int)(stream.Length - stream.Position)); stream = newStream; br = new BinaryReader(stream); // 判断剩下的是否包含一个完整的协议 stream.Position = 0; sumLen = br.ReadInt32(); } else { // 说明说是一个完整的包 stream = new MemoryStream(); br = new BinaryReader(stream); break; } } } catch (Exception ex) { UnityEngine.Debug.LogError("Decode protobuf fail!"); UnityEngine.Debug.LogException(ex); return(false); } return(true); }
private static Payload MakePayload <T>(T data, PayloadType type) where T : class { return(new Payload { Type = type, Data = ProtoSerializer.Serialize(data) }); }
public int Capacity(Soyo.Proto.ProtoTestClass value) { int capacity = 0; capacity += ProtoSerializer.Capacity(value.id); capacity += ProtoSerializer.ArrayCapacity(value.items); return(capacity); }
protected override void Test(FTestMessage message, Action <FTestMessage> customAssert = null) { using (var pool = ProtoSerializer.SerializePooled(message)) { var buf = pool.Item; var deserialized = ProtoSerializer.Deserialize <FTestMessage>(buf.Buffer, buf.Offset, buf.Count); AssertDeserialized(message, deserialized, customAssert); } }
public static Payload MakeTextPayload(string text, string replyToId, string messageId) { var textDataPayload = new TextDataPayload { Text = text }; var data = ProtoSerializer.Serialize(textDataPayload); return(MessageFactory.MakePayload(PayloadType.Text, replyToId, data, messageId)); }
public static CompiledSerializer Wrap(IProtoTypeSerializer head, TypeModel model) { CompiledSerializer serializer = head as CompiledSerializer; if (serializer == null) { serializer = new CompiledSerializer(head, model); } return(serializer); }
/// <summary> /// A helper method that creates content for the HTTPClient /// </summary> /// <param name="model"></param> /// <returns></returns> private ByteArrayContent createContent(TestModel model) { byte[] serializedModel = ProtoSerializer.Serialize(model); ByteArrayContent content = new ByteArrayContent(serializedModel); content.Headers.ContentType = new MediaTypeHeaderValue("application/x-protobuf"); return(content); }
protected override void Test(FTestMessage message, Action <FTestMessage> customAssert = null) { using (var ms = new MemoryStream()) { ProtoSerializer.Serialize(ms, message); ms.Position = 0; var deserialized = (FTestMessage)ProtoSerializer.Deserialize(typeof(FTestMessage), ms); AssertDeserialized(message, deserialized, customAssert); } }
private static FTestMessage FastWriteProtoReadOk(FTestMessage message) { var serialized = ProtoSerializer.Serialize(message); using (var ms = new MemoryStream(serialized)) { var deserialized = ProtoBuf.Serializer.Deserialize <PTestMessage>(ms); var fmsg = deserialized.ToMessage(); return(fmsg); } }
static CmdBroadcastRecv() { s_serializer = new ProtoSerializer(); s_handlers = new Dictionary <short, ProtoHandle>() { { Cmd.BroadcastRoomConf, new ProtoHandle() { ProtoType = typeof(RoomBroadCast), Handler = RecieveRoomConf } }, }; }
static CmdHandler() { s_serializer = new ProtoSerializer(); s_handlers = new Dictionary <short, ProtoHandle>() { { Cmd.LoginResponse, new ProtoHandle() { ProtoType = typeof(LoginResponse), Handler = LoginResponse } }, }; }
static CmdRequest() { s_serializer = new ProtoSerializer(); s_handlers = new Dictionary <short, ProtoHandle>() { { Cmd.LoginRequest, new ProtoHandle() { ProtoType = typeof(LoginRequest), Handler = LoginRequest } }, }; }
private async Task StartCheckBytesReadAsync() { while (true) { var timeout = this.Options.CheckBytesReadInterval.ToTimeoutChannel(); var cts = new CancellationTokenSource(); var channelTasks = new List <Task <Channel <uint?> > > { timeout.Shift(cts.Token), this.Context.DoneChannel.Shift(cts.Token) }; var channel = await channelTasks.FirstAsync(cts); if (channel == this.Context.DoneChannel) { throw this.Context.Error; } if (this.TotalBytesRead == 0 || this.AckSentTime > this.bytesReadUpdateTime || (DateTime.Now - this.bytesReadUpdateTime).TotalMilliseconds < this.Options.SendBytesReadThreshold) { continue; } try { var packet = new Packet { BytesRead = this.TotalBytesRead }; var data = ProtoSerializer.Serialize(packet); var tasks = new Task[this.connections.Count]; var i = 0; foreach (var connection in this.connections.Values) { tasks[i] = Task.Run(async() => await this.SendDataAsync(connection.LocalClientId, connection.RemoteClientId, data)); i++; } await Task.WhenAny(tasks); this.AckSentTime = DateTime.Now; } catch (Exception) { await Task.Delay(1000); continue; } } }
internal void SendAck(string destination, byte[] messageId, bool isEncrypted) { var payload = MessageFactory.MakeAckPayload(messageId.ToHexString(), null); var messagePayload = this.MakeMessageFromPayload(payload, isEncrypted, destination); var message = MessageFactory.MakeOutboundMessage( this, new string[] { destination }, new List <byte[]> { ProtoSerializer.Serialize(messagePayload) }, 0); this.SendThroughSocket(message.ToBytes()); }
private HttpClient GetClient() { var builder = new WebHostBuilder().Configure(app => { app.Use(async(context, next) => { context.Request.Headers.ValidateProtobuf(); await context.Response.Body.WriteAsync(ProtoSerializer.Serialize(_response)); }); }); var server = new TestServer(builder); return(server.CreateClient()); }
public int Capacity(Soyo.Proto.ProtoTestBase value) { int capacity = 0; capacity += ProtoSerializer.Capacity(value.byteValue); capacity += ProtoSerializer.Capacity(value.sbyteValue); capacity += ProtoSerializer.Capacity(value.shortValue); capacity += ProtoSerializer.Capacity(value.ushortValue); capacity += ProtoSerializer.Capacity(value.intValue); capacity += ProtoSerializer.Capacity(value.uintValue); capacity += ProtoSerializer.Capacity(value.longValue); capacity += ProtoSerializer.Capacity(value.ulongValue); capacity += ProtoSerializer.Capacity(value.floatValue); capacity += ProtoSerializer.Capacity(value.doubleValue); capacity += ProtoSerializer.Capacity((int)value.enumValue); capacity += ProtoSerializer.Capacity(value.stringValue); capacity += ProtoSerializer.Capacity(value.bufferValue); capacity += ProtoSerializer.Capacity(value.byteArrayValue); capacity += ProtoSerializer.Capacity(value.byteNullValue); capacity += ProtoSerializer.Capacity(value.sbyteNullValue); capacity += ProtoSerializer.Capacity(value.shortNullValue); capacity += ProtoSerializer.Capacity(value.ushortNullValue); capacity += ProtoSerializer.Capacity(value.intNullValue); capacity += ProtoSerializer.Capacity(value.uintNullValue); capacity += ProtoSerializer.Capacity(value.longNullValue); capacity += ProtoSerializer.Capacity(value.ulongNullValue); capacity += ProtoSerializer.Capacity(value.floatNullValue); capacity += ProtoSerializer.Capacity(value.doubleNullValue); capacity += ProtoSerializer.Capacity(value.bufferNullValue); capacity += ProtoSerializer.ArrayCapacity(value.boolListValue); capacity += ProtoSerializer.ArrayCapacity(value.byteListValue); capacity += ProtoSerializer.ArrayCapacity(value.sbyteListValue); capacity += ProtoSerializer.ArrayCapacity(value.shortListValue); capacity += ProtoSerializer.ArrayCapacity(value.ushortListValue); capacity += ProtoSerializer.ArrayCapacity(value.intListValue); capacity += ProtoSerializer.ArrayCapacity(value.uintListValue); capacity += ProtoSerializer.ArrayCapacity(value.longListValue); capacity += ProtoSerializer.ArrayCapacity(value.ulongListValue); capacity += ProtoSerializer.ArrayCapacity(value.floatListValue); capacity += ProtoSerializer.ArrayCapacity(value.doubleListValue); capacity += ProtoSerializer.ArrayCapacity(value.stringListValue); capacity += ProtoSerializer.ArrayCapacity(value.bufferListValue); capacity += ProtoSerializer.ArrayCapacity(value.byteArrayListValue); capacity += ProtoSerializer.Capacity(value.boolValue); capacity += ProtoSerializer.Capacity(value.boolNullValue); capacity += ProtoSerializer.DictionaryCapacity(value.uintUintDictionary); return(capacity); }
public Soyo.Proto.ProtoTestBase DeepCopy(Soyo.Proto.ProtoTestBase dst, Soyo.Proto.ProtoTestBase src) { dst.byteValue = src.byteValue; dst.sbyteValue = src.sbyteValue; dst.shortValue = src.shortValue; dst.ushortValue = src.ushortValue; dst.intValue = src.intValue; dst.uintValue = src.uintValue; dst.longValue = src.longValue; dst.ulongValue = src.ulongValue; dst.floatValue = src.floatValue; dst.doubleValue = src.doubleValue; dst.enumValue = src.enumValue; dst.stringValue = src.stringValue; dst.bufferValue = src.bufferValue; dst.byteArrayValue = ProtoSerializer.DeepCopy(dst.byteArrayValue, src.byteArrayValue); dst.byteNullValue = src.byteNullValue; dst.sbyteNullValue = src.sbyteNullValue; dst.shortNullValue = src.shortNullValue; dst.ushortNullValue = src.ushortNullValue; dst.intNullValue = src.intNullValue; dst.uintNullValue = src.uintNullValue; dst.longNullValue = src.longNullValue; dst.ulongNullValue = src.ulongNullValue; dst.floatNullValue = src.floatNullValue; dst.doubleNullValue = src.doubleNullValue; dst.bufferNullValue = src.bufferNullValue; dst.boolListValue = ProtoSerializer.DeepCopy(dst.boolListValue, src.boolListValue); dst.byteListValue = ProtoSerializer.DeepCopy(dst.byteListValue, src.byteListValue); dst.sbyteListValue = ProtoSerializer.DeepCopy(dst.sbyteListValue, src.sbyteListValue); dst.shortListValue = ProtoSerializer.DeepCopy(dst.shortListValue, src.shortListValue); dst.ushortListValue = ProtoSerializer.DeepCopy(dst.ushortListValue, src.ushortListValue); dst.intListValue = ProtoSerializer.DeepCopy(dst.intListValue, src.intListValue); dst.uintListValue = ProtoSerializer.DeepCopy(dst.uintListValue, src.uintListValue); dst.longListValue = ProtoSerializer.DeepCopy(dst.longListValue, src.longListValue); dst.ulongListValue = ProtoSerializer.DeepCopy(dst.ulongListValue, src.ulongListValue); dst.floatListValue = ProtoSerializer.DeepCopy(dst.floatListValue, src.floatListValue); dst.doubleListValue = ProtoSerializer.DeepCopy(dst.doubleListValue, src.doubleListValue); dst.stringListValue = ProtoSerializer.DeepCopy(dst.stringListValue, src.stringListValue); dst.bufferListValue = ProtoSerializer.DeepCopy(dst.bufferListValue, src.bufferListValue); dst.byteArrayListValue = ProtoSerializer.DeepCopy(dst.byteArrayListValue, src.byteArrayListValue); dst.boolValue = src.boolValue; dst.boolNullValue = src.boolNullValue; dst.uintUintDictionary = ProtoSerializer.DeepCopy(dst.uintUintDictionary, src.uintUintDictionary); return(dst); }
private void LoadSettings() { if (!File.Exists(PathManager.SettingsFileName)) { Settings = new Settings(); } else { try { var data = File.ReadAllBytes(PathManager.SettingsFileName); Settings = ProtoSerializer.Deserialize <Settings>(data) ?? new Settings(); } catch (Exception ex) { AppLogger.Error(ex, "Failed load settings."); } } }
public static void Test(object obj, ProtoSerializer serializer, string message, byte[] expected) { byte[] data; using (MemoryStream ms = new MemoryStream()) { int reported; using (ProtoWriter writer = new ProtoWriter(ms, RuntimeTypeModel.Default, null)) { serializer(obj, writer); reported = ProtoWriter.GetPosition(writer); } data = ms.ToArray(); Assert.Equal(reported, data.Length); //, message + ":reported/actual"); } Assert.Equal(expected.Length, data.Length); //, message + ":Length"); for (int i = 0; i < data.Length; i++) { Assert.Equal(expected[i], data[i]); //, message + ":" + i); } }
public void ComplexType_SerailizeAndBack_ValuesAreEqual() { var value = new Team { Name = "av_team", Memebers = new[] { new User { Name = "Kolya", Age = 24, IsFemale = false }, new User { Name = "Petya", Age = 2, IsFemale = false }, new User { Name = "Sasha", Age = 3, IsFemale = false } } }; using (var result = new MemoryStream()) { var primitiveSerializator = new ProtoSerializer <Team>(); primitiveSerializator.SerializeT(value, result); result.Position = 0; var deserialized = new ProtoDeserializer <Team>().DeserializeT(result, (int)result.Length); Assert.IsNotNull(deserialized); Assert.IsTrue(value.IsSameTo(deserialized)); } }