public void Set(JiraSettings jiraSettings) { byte[] serializedJiraSettings = _binarySerializer.Serialize <JiraSettings, JiraSettingsProtobufContract>(jiraSettings); EncryptedData encryptedJiraSettings = _dataEncryptor.Encrypt(serializedJiraSettings); byte[] serializedEncryptedJiraSettings = _binarySerializer.Serialize <EncryptedData, EncryptedDataProtobufContract>(encryptedJiraSettings); _applicationStorageFolder.StoreBytes(JiraSettingsFileName, serializedEncryptedJiraSettings); }
public void ExpreessionInfoCloneTest2() { ExpressionInfo canRun = ExpressionInfo.Eq( ExpressionInfo.PrimitiveVal(CmdResultCode.Success), ExpressionInfo.Val(new TaskInputInfo())); Assert.DoesNotThrow(() => { TaskInfo task = new TaskInfo { Expression = canRun }; byte[] b = m_protobufSerializer.Serialize(SerializedTask.FromTaskInfo(task)); SerializedTask.ToTaskInfo(m_protobufSerializer.Deserialize <SerializedTask>(b)); }); }
public void Json_Serialize_Deserialize_Test() { using (ProtobufSerializer serializer = new ProtobufSerializer()) { Person person = new Person() { Id = 2, Name = "Jerry" }; byte[] buffer = serializer.Serialize(person); Person _person = serializer.Deserialize <Person>(buffer); Assert.Equal(person.Id, _person.Id); Assert.Equal(person.Name, _person.Name); JsonObject json = new JsonObject(typeof(Person).FullName, buffer); string jsonstr = JsonFormatter.SerializeObject(json); JsonObject _json = JsonFormatter.DeserializeObject <JsonObject>(jsonstr); JsonObject <Person> jsont = new JsonObject <Person>(typeof(Person).FullName, person); string jsontstr = JsonFormatter.SerializeObject(jsont); JsonObject <Person> _jsont = JsonFormatter.DeserializeObject <JsonObject <Person> >(jsontstr); } }
public void SendMessage(string key, object msg) { if (!connected) { Debug.LogError("没有连接到服务器!"); return; } byte[] buff = null; MemoryStream stream = new MemoryStream(); serializer.Serialize(stream, msg); buff = stream.ToArray(); MemoryStream strm = new MemoryStream(); byte[] msgLenBytes = System.BitConverter.GetBytes((Int16)(buff.Length + 2)); strm.Write(msgLenBytes, 0, msgLenBytes.Length); byte[] msgIdBytes = System.BitConverter.GetBytes(NetIDContainer.GetMessageId(key)); Debug.Log("=======发送:" + key); strm.Write(msgIdBytes, 0, msgIdBytes.Length); strm.Write(buff, 0, buff.Length); byte[] toSendBytes = strm.ToArray(); m_stream.Write(toSendBytes, 0, toSendBytes.Length); }
private void Start() { pb.PlayerSnapShootMsg msg = new pb.PlayerSnapShootMsg(); msg.username = "******"; msg.playerId = 9000001; byte[] data = ProtobufSerializer.Serialize(msg); Debug.LogError("data len " + data.Length); ByteBuffer buffer = ByteBuffer.Allocate(1024); buffer.WriteShort(1001); buffer.WriteShort(1002); buffer.WriteShort(1003); buffer.WriteLong(10055555); buffer.WriteBytes(data); short s1 = buffer.ReadShort(); short s2 = buffer.ReadShort(); short s3 = buffer.ReadShort(); long l1 = buffer.ReadLong(); byte[] readData = new byte[buffer.ReadableBytes()]; buffer.ReadBytes(readData, 0, buffer.ReadableBytes()); Debug.LogError("readData len " + readData.Length); pb.PlayerSnapShootMsg dmsg = ProtobufSerializer.DeSerialize <pb.PlayerSnapShootMsg>(readData); Debug.LogError("user name " + dmsg.username); //socket receive bytes // }
public void ValidateRequestSerialization() { // Arrange IRequestMessage sent = factory.CreateRequestMessage("cat", "ICalculator", "Add", new object[] { 5, 6 }, true); // Act IRequestMessage received = (IRequestMessage)serializer.Deserialize(serializer.Serialize(sent)); (received as IIncomplete).Complete(typeof(ICalculator).GetMethod(nameof(ICalculator.Add))); // Assert Assert.AreEqual(sent.IsResponseExpected, received.IsResponseExpected); CollectionAssert.AreEqual(sent.Args, received.Args); Assert.AreEqual(sent.MethodName, received.MethodName); Assert.AreEqual(sent.CorrelationId, received.CorrelationId); Assert.AreEqual(sent.MessageType, received.MessageType); }
public void Serialize_Poco_NotNull() { var serializer = new ProtobufSerializer(); var poco = new Poco(); var data = serializer.Serialize(poco); Assert.NotNull(data); }
/// <summary> /// 读写器层协议转换为protoBuf格式 /// </summary> /// <param name="message"></param> /// <returns></returns> public static byte[] ReaderCommandToProtobuf(string[] message) { string ms = string.Empty; Message ob = StringToModel.StrToModel(message); // ms = ProtobufSerializer.Serialize<Message>(ob); ms = ProtobufSerializer.Serialize <Message>(ob); return(System.Text.Encoding.Unicode.GetBytes(ms)); // return ms; }
public void emtpy_or_just_created_header_should_take_zero_bytes_when_serialized() { var header = new Header(); var serializer = new ProtobufSerializer(); var bytes = serializer.Serialize(header); var back = serializer.Deserialize <Header>(bytes); Assert.That(bytes.Length, Is.EqualTo(0)); }
public void Save(Action <byte[]> done) { if (m_isBusy) { throw new InvalidOperationException("m_isBusy"); } m_isBusy = true; m_progressIndicator.IsVisible = true; m_progressIndicator.SetText("Saving..."); m_job.Submit( () => { ProtobufSerializer serializer = null; byte[] bytes = null; try { var pool = Dependencies.Serializer; if (pool != null) { serializer = pool.Acquire(); bytes = serializer.Serialize(Map); } } finally { if (serializer != null) { var pool = Dependencies.Serializer; if (pool != null) { pool.Release(serializer); } } } return(bytes); }, result => { m_isBusy = false; m_progressIndicator.IsVisible = false; if (Saved != null) { Saved(this, EventArgs.Empty); } if (done != null) { done((byte[])result); } }); }
virtual public void request() { ProtobufSerializer serializer = new ProtobufSerializer(); //using (MemoryStream temp = new MemoryStream()) serializer.Serialize(m_bytes, req); //m_bytes.Position = 0; CNetWorkGlobal.Instance.SendProto(this); }
public void Protobuf_Serialize_Deserialize_Test() { using (ProtobufSerializer serializer = new ProtobufSerializer()) { Person person = new Person() { Id = 2, Name = "Jerry", Address = new Address() }; byte[] buffer = serializer.Serialize(person); Person _person = serializer.Deserialize <Person>(buffer); Assert.Equal(person.Id, _person.Id); Assert.Equal(person.Name, _person.Name); ProtobufMessagePack <Person> pack = new ProtobufMessagePack <Person>(person); buffer = serializer.Serialize(pack); _person = serializer.Deserialize <ProtobufMessagePack <Person> >(buffer)?.Message; Assert.Equal(person.Id, _person.Id); Assert.Equal(person.Name, _person.Name); Packet packet = new Packet(typeof(Person).FullName, buffer, PacketType.Join, Guid.NewGuid().ToString()); buffer = serializer.Serialize(new ProtobufPacket(packet)); ProtobufPacket _packet = serializer.Deserialize <ProtobufPacket>(buffer); Assert.Equal(packet.PackType, _packet.PackType); Assert.Equal(packet.PacketType, _packet.PacketType); Assert.Equal(packet.FromId, _packet.FromId); _person = serializer.Deserialize <ProtobufMessagePack <Person> >(_packet.Payload)?.Message; Assert.Equal(person.Id, _person.Id); Assert.Equal(person.Name, _person.Name); } }
/* * public string RootPath * { * get{ #if UNITY_EDITOR * string rootPath = Application.dataPath ; #else * string rootPath = Application.persistentDataPath; #endif * string folder = rootPath + protoPath; * return folder; * } * } * * public T LoadProtoData<T> (string name) * { * //string md5Name = CommonUtils.GenerateMD5 (Encoding.UTF8.GetBytes (name)); * * string path = RootPath + name + ".bytes"; * * Debug.Assert(File.Exists(path),"No file at path :" + path); * * DebugUtils.Log (DebugUtils.Type.Data, "load proto file " + name + ", path = " + path); * byte[] data = File.ReadAllBytes (path); * return Deserialize<T> (data); * } * * public void SavaProtoData (byte[] data, string fileName) * { * Stream sw; * * //string md5Name = CommonUtils.GenerateMD5 (Encoding.UTF8.GetBytes (fileName)); * * string folder = RootPath ; * if(!Directory.Exists(folder)){ * Directory.CreateDirectory(folder); * } * * string path = folder + fileName + ".bytes"; * DebugUtils.Log (DebugUtils.Type.Data, "path: " + path + " originName : " + fileName); * FileInfo f = new FileInfo (path); * if (f.Exists) { * f.Delete (); * f = new FileInfo (path); * sw = f.Create (); * } else { * sw = f.Create (); * } * sw.Write (data, 0, data.Length); * sw.Close (); * sw.Dispose (); * } */ /* * public static byte[] Serialize<T>( T dataObject ) * { * DebugUtils.Assert( dataObject != null ); * byte[] buffer = null; * using( MemoryStream m = new MemoryStream() ) // use a cached memory stream instead? * { * Serializer.Serialize<T>( m, dataObject ); * m.Position = 0; * int length = (int)m.Length; * buffer = new byte[length]; * m.Read( buffer, 0, length ); * } * return buffer; * } * * public static T Deserialize<T>( byte[] data ) * { * DebugUtils.Assert( data != null && data.Length > 0 ); * T dataObject; * using( MemoryStream m = new MemoryStream( data ) ) * { * dataObject = Serializer.Deserialize<T>( m ); * } * return dataObject; * } */ public static byte[] Serialize(object dataObject) { DebugUtils.Assert(dataObject != null); byte[] buffer = null; using (MemoryStream m = new MemoryStream()) { // use a cached memory stream instead? serializer.Serialize(m, dataObject); m.Position = 0; int length = (int)m.Length; buffer = new byte[length]; m.Read(buffer, 0, length); } return(buffer); }
public void Serialize_Default() { var model = new Model() { Bar = 15, Foo = "foo" }; IRedisSerializer protobufSerializer = new ProtobufSerializer() { CompressionFormat = CompressionFormat.None }; var redisValue = protobufSerializer.Serialize(model); Assert.True(redisValue.HasValue); }
public void simple_test() { var header = new Header(); header.Set("Hello", "World"); var serializer = new ProtobufSerializer(); var bytes = serializer.Serialize(header); var back = serializer.Deserialize <Header>(bytes); Assert.That(back.GetString("Hello"), Is.EqualTo("World")); Assert.That(back.GetString("Hello"), Is.EqualTo(header.GetString("Hello"))); }
public static byte[] SerializeProtocol <T>(T kPB) { MemoryStream kStream = new MemoryStream(); try { protobufSerializer.Serialize(kStream, kPB); return(kStream.ToArray()); } catch { Debug.LogError("Can't Encode PB " + typeof(T).Name); return(null); } }
public void Deserialize_GZip() { var model = new Model() { Bar = 15, Foo = "foo" }; IRedisSerializer protobufSerializer = new ProtobufSerializer() { CompressionFormat = CompressionFormat.GZip }; var deserialized = protobufSerializer.Deserialize <Model>(protobufSerializer.Serialize(model)); Assert.Equal(model.Bar, deserialized.Bar); Assert.Equal(model.Foo, deserialized.Foo); }
public void ShouldSerializeServerToClientMessage() { var serializer = new ProtobufSerializer(); for (int i = 0; i < 1000; i++) { var s = serializer.Serialize(new ServerToClientMessage { MessageType = ServerToClientMessageTypeEnum.LimitOrderAccepted }); Assert.IsNotNull(s); var d = serializer.Deserialize <ServerToClientMessage>(s); Assert.IsNotNull(d); } }
public void SerializationPerformanceTest() { var sw = new Stopwatch(); var serializer = new ProtobufSerializer(); var instance = new ServerToClientMessage(); sw.Start(); for (int i = 0; i < 5000000; i++) serializer.Serialize(instance); sw.Stop(); var elapsed = sw.ElapsedMilliseconds; double perItem = (double)elapsed/(double)5000000; Console.WriteLine("Total ms: " + elapsed); Console.WriteLine("Per item: " + perItem); }
void Awake() { MemoryStream ms = new MemoryStream(); ActiveCodeReqPROTO ace = new ActiveCodeReqPROTO(); ace.AccountId = 10000000000000001; ace.ActiveCode = "lyw"; ProtobufSerializer serializer = new ProtobufSerializer(new TypeModelProtobufSerializer()); serializer.Serialize(ms, ace); MemoryStream memoryStream = new MemoryStream(ms.ToArray()); ActiveCodeReqPROTO activeCodeReq = (ActiveCodeReqPROTO)serializer.Deserialize(memoryStream, typeof(ActiveCodeReqPROTO)); Debug.LogError(string.Format("AccountId = {0}, ActiveCode = {1}", activeCodeReq.AccountId, activeCodeReq.ActiveCode)); }
public static byte[] Encode(object msg) { if (m_DicIDName.ContainsKey(msg.GetType())) { m_Stream.SetLength(0); m_Serializer.Serialize(m_Stream, msg); byte[] ret = new byte[2 + m_Stream.Length]; int id = m_DicIDName[msg.GetType()]; ret[0] = (byte)(id >> 8); ret[1] = (byte)(id); m_Stream.Position = 0; m_Stream.Read(ret, 2, ret.Length - 2); return(ret); } else { return(null); } }
public void SerializeDeserializeTest() { var serializer = new ProtobufSerializer(); var byteArray = new RingbufferByteArray(); var item = new ServerToClientMessage(); item.Message = "hello"; item.MessageType = ServerToClientMessageTypeEnum.LimitOrderAccepted; byteArray.Set(serializer.Serialize(item)); byte[] target = new byte[512]; byteArray.GetContent(ref target); var deserialized = serializer.Deserialize<ServerToClientMessage>(target.Take(byteArray.ContentLength).ToArray()); Assert.IsNotNull(deserialized); Assert.AreEqual("hello", deserialized.Message); Assert.AreEqual(ServerToClientMessageTypeEnum.LimitOrderAccepted, deserialized.MessageType); }
public void DeserializeAccount() { IAElfSerializer serializer = new ProtobufSerializer(); /* Create account and print adress */ ProtoAccount account = new ProtoAccount(); account.PAddress = ByteString.CopyFrom(GetRandomBytes(10)); PrintBytes(account.PAddress.ToByteArray()); /* Serialize and print */ byte[] serializedAccount = serializer.Serialize(account); PrintBytes(serializedAccount); /* Deserialize and check address */ ProtoAccount deserializedAcc = serializer.Deserialize <ProtoAccount>(serializedAccount); PrintBytes(deserializedAcc.PAddress.ToByteArray()); }
public void SerializeDeserializeTest() { var serializer = new ProtobufSerializer(); var byteArray = new RingbufferByteArray(); var item = new ServerToClientMessage(); item.Message = "hello"; item.MessageType = ServerToClientMessageTypeEnum.LimitOrderAccepted; byteArray.Set(serializer.Serialize(item)); byte[] target = new byte[512]; byteArray.GetContent(ref target); var deserialized = serializer.Deserialize <ServerToClientMessage>(target.Take(byteArray.ContentLength).ToArray()); Assert.IsNotNull(deserialized); Assert.AreEqual("hello", deserialized.Message); Assert.AreEqual(ServerToClientMessageTypeEnum.LimitOrderAccepted, deserialized.MessageType); }
private static void ProtobufSerialize(object obj, Stream stream) { if (obj == null) { return; } if (obj is DataSet) { ProtobufDataSetSerializer.ProtoWrite(obj as DataSet, stream); } else if (obj is DataTable) { ProtobufDataTableSerializer.ProtoWrite(obj as DataTable, stream); } else { ProtobufSerializer.Serialize <object>(stream, obj); } }
public void DeSerializationPerformanceTest() { var sw = new Stopwatch(); var serializer = new ProtobufSerializer(); var instance = new ServerToClientMessage(); var serialized = serializer.Serialize(instance); sw.Start(); for (int i = 0; i < 5000000; i++) { serializer.Deserialize <ServerToClientMessage>(serialized); } sw.Stop(); var elapsed = sw.ElapsedMilliseconds; double perItem = (double)elapsed / (double)5000000; Console.WriteLine("Total ms: " + elapsed); Console.WriteLine("Per item: " + perItem); }
public void Test_Untyped() { var rnd = new Random(); var record = new TestRecord { Id = Guid.NewGuid().ToString(), Integer = DateTime.UtcNow.Millisecond, Floating = rnd.NextDouble(), EnumeratedValue = MyEnum.Val2, TextValues = { rnd.Next().ToString(), rnd.Next().ToString(), rnd.Next().ToString(), rnd.Next().ToString() } }; byte[] bytes; // serialize to bytes var ser = new ProtobufSerializer(); bytes = ser.Serialize(record, default); TestRecord testing; // back to object var deSer = new ProtobufDeserializer <TestRecord>(); testing = deSer.Deserialize(bytes, false, default); Assert.AreEqual(record.Id, testing.Id); Assert.AreEqual(record.Integer, testing.Integer); Assert.AreEqual(record.Floating, testing.Floating); Assert.AreEqual(record.EnumeratedValue, testing.EnumeratedValue); Assert.AreEqual(record.TextValues.Count, testing.TextValues.Count); for (int i = 0; i < record.TextValues.Count; i++) { Assert.AreEqual(record.TextValues[i], testing.TextValues[i]); } }
private void Test(IEnumerable <Type> messageTypes, IEnumerable <Type> identityType, params Object[] objects) { var map = new Dictionary <Object, byte[]>(); var messageTypeList = messageTypes.ToList(); var identityTypeList = identityType.ToList(); var messageFactory = new MessageFactory(messageTypeList); var identityFactory = new IdentityFactory(identityTypeList); var serializer = new ProtobufSerializer(); serializer.RegisterMessages(messageFactory.MessageDefinitions); serializer.RegisterIdentities(identityFactory.IdentityDefinitions); foreach (var obj in objects) { map[obj] = serializer.Serialize(obj); } // reverse order of messages and identities messageTypeList.Reverse(); identityTypeList.Reverse(); messageFactory = new MessageFactory(messageTypeList); identityFactory = new IdentityFactory(identityTypeList); serializer = new ProtobufSerializer(); serializer.RegisterMessages(messageFactory.MessageDefinitions); serializer.RegisterIdentities(identityFactory.IdentityDefinitions); foreach (object obj in objects) { var back = serializer.Deserialize(map[obj], obj.GetType()); var result = ObjectComparer.AreObjectsEqual(obj, back); Assert.That(result, Is.True); } }
public void Coder_Test() { using (ProtobufSerializer serializer = new ProtobufSerializer()) { Person person = new Person() { Id = 2, Name = "Jerry", Address = new Address() }; byte[] buffer = serializer.Serialize(person); PacketCoder coder = new PacketCoder(); byte[] _buffer = coder.Encode(buffer); List <byte> lst = new List <byte>(); lst.AddRange(buffer); lst.AddRange(_buffer); lst.AddRange(_buffer); lst.AddRange(_buffer); lst.AddRange(buffer); Queue <byte[]> queue = new Queue <byte[]>(); byte[] _buffer_ = lst?.ToArray(); byte[][] __buffer = coder.Decode(_buffer_, out int _); foreach (var item in __buffer) { Person _person = serializer.Deserialize <Person>(item); System.Console.WriteLine($"Id:{_person.Id},Name:{_person.Name}"); Assert.Equal(person.Id, _person.Id); Assert.Equal(person.Name, _person.Name); } System.Console.WriteLine(_buffer_?.Length); } }
private void Update() { if (Input.GetKeyDown(KeyCode.V)) { int HEAD_LEN = 18;//包头长度 short HEAD_FIX = 0x71ab; pb.PlayerSnapShootMsg msg = new pb.PlayerSnapShootMsg(); msg.playerId = 80000060; msg.username = "******"; byte[] data = ProtobufSerializer.Serialize <pb.PlayerSnapShootMsg>(msg); int len = data.Length; ByteBuffer buffer = ByteBuffer.Allocate(len + HEAD_LEN); buffer.WriteShort(HEAD_FIX); buffer.WriteShort((short)(HEAD_LEN + len)); buffer.WriteShort(12001); buffer.WriteLong(90000001001); buffer.WriteInt(0); buffer.WriteBytes(data); GameSocket.Instance.Send(buffer); Debug.LogError("发送一条消息给服务器1"); } }
public void ShouldSerializeAndDeserializeSeriesOfItems() { var serializer = new ProtobufSerializer(); for (int i = 0; i < 1000; i++) { var item = new ServerToClientMessage(); item.Message = i.ToString(); item.MessageType = ServerToClientMessageTypeEnum.LimitOrderAccepted; item.LimitOrder = new LimitOrderDto(); item.LimitOrder.ClientId = i; item.LimitOrder.ExchangeOrderId = (uint)i; var serialized = serializer.Serialize(item); var deserialized = serializer.Deserialize <ServerToClientMessage>(serialized); Assert.IsNotNull(deserialized); Assert.AreEqual(i.ToString(), deserialized.Message); Assert.AreEqual(ServerToClientMessageTypeEnum.LimitOrderAccepted, deserialized.MessageType); Assert.AreEqual(i, deserialized.LimitOrder.ClientId); Assert.AreEqual(i, deserialized.LimitOrder.ExchangeOrderId); } }
public void ShouldSerializeAndDeserializeSeriesOfItems() { var serializer = new ProtobufSerializer(); for (int i = 0; i < 1000; i++) { var item = new ServerToClientMessage(); item.Message = i.ToString(); item.MessageType = ServerToClientMessageTypeEnum.LimitOrderAccepted; item.LimitOrder = new LimitOrderDto(); item.LimitOrder.ClientId = i; item.LimitOrder.ExchangeOrderId = (uint)i; var serialized = serializer.Serialize(item); var deserialized = serializer.Deserialize<ServerToClientMessage>(serialized); Assert.IsNotNull(deserialized); Assert.AreEqual(i.ToString(), deserialized.Message ); Assert.AreEqual(ServerToClientMessageTypeEnum.LimitOrderAccepted, deserialized.MessageType); Assert.AreEqual(i, deserialized.LimitOrder.ClientId); Assert.AreEqual(i, deserialized.LimitOrder.ExchangeOrderId); } }
public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content) { ISerializer serializer = new ProtobufSerializer(); serializer.Serialize(value, writeStream); }
public static void ProtobufTest(int seed) { ProtobufSerializer serializer = new ProtobufSerializer(); Mall mall = new Mall() { ID = 1, Name = "大悦城", GroupID = 135 }; Stopwatch sw = new Stopwatch(); byte[] data = null; sw.Restart(); for (var i = 0; i < seed; i++) { data = serializer.Serialize(mall); } sw.Stop(); Console.WriteLine("ProtobufTest Serialize:{0}ms", sw.ElapsedMilliseconds); SpinWait.SpinUntil(() => false, 500); sw.Restart(); for (var i = 0; i < seed; i++) { mall = serializer.Deserialize<Mall>(data); } sw.Stop(); Console.WriteLine("ProtobufTest Deserialize:{0}ms", sw.ElapsedMilliseconds); }
public void ShouldSerializeServerToClientMessage() { var serializer = new ProtobufSerializer(); for (int i = 0; i < 1000; i++) { var s = serializer.Serialize(new ServerToClientMessage {MessageType = ServerToClientMessageTypeEnum.LimitOrderAccepted}); Assert.IsNotNull(s); var d = serializer.Deserialize<ServerToClientMessage>(s); Assert.IsNotNull(d); } }