Beispiel #1
0
        public T From <T>(byte[] data, Type messageType)
        {
            if (data is null || data.Length == 0)
            {
                Throw.ArgumentException(nameof(data), "Cannot be null or empty");
            }

            return((T)_serialisers.GetOrAdd(messageType, key => MessagePackSerializer.Get(key))
                   .UnpackSingleObject(data));
        }
        public byte[] Serialize <T>(T thisObj)
        {
            var serializer = MessagePackSerializer.Get <T>();

            using (var byteStream = new MemoryStream())
            {
                serializer.Pack(byteStream, thisObj);
                return(byteStream.ToArray());
            }
        }
Beispiel #3
0
        /// <summary>
        /// 二进制反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        public T DeSerialize <T>(byte[] data)
        {
            using (MemoryStream memoryStream = new MemoryStream(data))
            {
                var ser = MessagePackSerializer.Get <T>(context);

                var obj = ser.Unpack(memoryStream);
                return(obj);
            }
        }
Beispiel #4
0
        /// <summary>
        /// 二进制序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public byte[] Serialize <T>(T obj)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                var ser = MessagePackSerializer.Get <T>(context);

                ser.Pack(memoryStream, obj);
                return(memoryStream.ToArray());
            }
        }
Beispiel #5
0
        public byte[] AsBytes <T>(T entity)
        {
            if (entity is null)
            {
                Throw.ArgumentNullException(nameof(entity));
            }

            return(_serialisers.GetOrAdd(typeof(T), key => MessagePackSerializer.Get(key))
                   .PackSingleObject(entity));
        }
Beispiel #6
0
        private void Send <TRequest>(RequestHeader header, TRequest request)
        {
            // Pack the header and the body
            var packer1 = MessagePackSerializer.Get <RequestHeader>();
            var packer2 = MessagePackSerializer.Get <TRequest>();

            packer1.Pack(this.Stream, header);
            packer2.Pack(this.Stream, request);
            this.Stream.Flush();
        }
Beispiel #7
0
        public T Unpack <T>(byte[] bytes) where T : MetaObject
        {
            var serializer = MessagePackSerializer.Get <MetaObject>(serializationContext);

            var tempObject = serializer.UnpackSingleObject(bytes);
            var type       = TypeForEnum(tempObject.Type);

            var objectSerializer = MessagePackSerializer.Get(type, serializationContext);

            return((T)objectSerializer.UnpackSingleObject(bytes));
        }
Beispiel #8
0
        /// <summary>
        /// Invokes the handler with the specified response object.
        /// </summary>
        public void Process(MemoryStream stream)
        {
            // Unpack the response with the custom context
            var packer = MessagePackSerializer.Get <T>(SerfClient.Context);

            //var response = packer.UnpackSingleObject(buffer);
            var response = packer.Unpack(stream);

            // Invoke the handler with typed parameter
            this.Handler(response);
        }
Beispiel #9
0
        private void SendDataToServer()
        {
            var sendMsg = MessagePackSerializer.Get <SimpleFrame>();

            using (var stream = new MemoryStream())
            {
                sendMsg.Pack(stream, _ipcMsg);
                _data = stream.ToArray();
            }
            Client.Send(_data, _data.Length);
        }
Beispiel #10
0
        private SuperBlock ReadSuperBlock()
        {
            SuperBlock SuperBlock = null;

            byte[] SuperBlockBuffer = new byte[100];
            ArchivFile.Read(SuperBlockBuffer, 0, 100);
            MessagePackSerializer MessagePackSerializer = MessagePackSerializer.Get <SuperBlock>();

            SuperBlock = (SuperBlock)MessagePackSerializer.UnpackSingleObject(SuperBlockBuffer);
            return(SuperBlock);
        }
        protected MemoryStream CreateSerializedObject <T>(T sample)
        {
            var serializer = MessagePackSerializer.Get <T>();
            var ms         = new MemoryStream();

            serializer.Pack(ms, sample);

            ms.Position = 0;

            return(ms);
        }
Beispiel #12
0
        /// <summary>
        /// The unpack.
        /// </summary>
        /// <param name="data">
        /// The data.
        /// </param>
        /// <returns>
        /// The <see cref="BaseMessage"/>.
        /// </returns>
        public static BaseMessage Unpack(byte[] data)
        {
            if (serializer == null)
            {
                serializer = MessagePackSerializer.Get <DynamicMessage>();
            }

            DynamicMessage dm = serializer.UnpackSingleObject(data);

            return(dm.DataObject);
        }
Beispiel #13
0
        /// <summary>Internal usage, shouldn't be called.</summary>
        public void ApplyPatch(byte[] delta)
        {
            this._previousState = Fossil.Delta.Apply(this._previousState, delta);

            var serializer = MessagePackSerializer.Get <MessagePackObject>();
            var newState   = serializer.UnpackSingleObject(this._previousState);

            this.state.Set(newState);
            //this.state = state
            this.OnUpdate.Invoke(this, new RoomUpdateEventArgs(this, this.state.data, null));
        }
        /// <summary>
        /// Deserializes the specified data.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public T Deserialize <T>(RedisValue data)
        {
            if (data.HasValue)
            {
                using (var ms = new MemoryStream(data))
                {
                    return(MessagePackSerializer.Get <T>().Unpack(ms));
                }
            }

            return(default);
Beispiel #15
0
        /// <summary>
        /// シリアライズを行なう
        /// </summary>
        public override void GetData(object target, Stream outgoingData)
        {
            var context = new SerializationContext();

            context.SerializationMethod = SerializationMethod.Map;

            var serializer = MessagePackSerializer.Get(target.GetType(), context);

            serializer.Pack(outgoingData, target);
            outgoingData.Position = 0;
        }
        private int LoadTest(string filepath)
        {
            var serializer = MessagePackSerializer.Get <List <MotionData> >();
            List <MotionData> mdns;

            using (FileStream fs = File.Open(filepath, FileMode.Open))
            {
                mdns = (List <MotionData>)serializer.Unpack(fs);
            }
            return(mdns.Count());
        }
Beispiel #17
0
        public static async Task <T?> UnPackAsync <T>(byte[]?bytes) where T : class
        {
            if (bytes.IsNullOrEmpty())
            {
                return(null);
            }

            MessagePackSerializer <T> serializer = MessagePackSerializer.Get <T>();

            return(await serializer.UnpackSingleObjectAsync(bytes).ConfigureAwait(false));
        }
Beispiel #18
0
    /// <summary>
    /// Serializes specified object to the <see cref="T:System.IO.Stream" /> asynchronously.
    /// </summary>
    /// <param name="value"></param>
    /// <param name="stream"></param>
    /// <param name="cancellationToken"></param>
    /// <typeparam name="TValue"></typeparam>
    /// <returns></returns>
    /// <exception cref="T:System.ArgumentNullException">
    ///     <paramref name="stream" /> is <c>null</c>.
    /// </exception>
    /// <exception cref="T:System.Runtime.Serialization.SerializationException">
    ///     Failed to serialize object.
    /// </exception>
    /// <exception cref="T:System.NotSupportedException">
    ///     <typeparamref name="TValue" /> is not serializable even if it can be deserialized.
    /// </exception>
    /// <seealso cref="P:Capabilities" />
    public static async Task PackAsync <TValue>(TValue?value, Stream?stream,
                                                CancellationToken cancellationToken = default)
    {
        if (stream is null)
        {
            return;
        }
        await MessagePackSerializer.Get <TValue>().PackAsync(stream, value, cancellationToken);

        stream.TrySeek(0, SeekOrigin.Begin);
    }
 public T Deserialize <T>(byte[] buffer)
 {
     using (MemoryStream stream = new MemoryStream(buffer))
     {
         stream.Position = 0L;
         // Creates serializer.
         var serializer = MessagePackSerializer.Get <T>();
         // Unpack from stream.
         return(serializer.Unpack(stream));
     }
 }
Beispiel #20
0
        /// <summary>
        /// 购买金币
        /// </summary>
        /// <param name="sShopID"></param>
        /// <param name="sItemIndex"></param>
        public void BuyGoldReqDef(short sShopID, short sItemIndex)
        {
            BaseMessage.BuyGoldReqDef BuyGoldReq = new BaseMessage.BuyGoldReqDef();
            BuyGoldReq.sShopID    = sShopID;
            BuyGoldReq.sItemIndex = sItemIndex;
            var serializer = MessagePackSerializer.Get <BaseMessage.BuyGoldReqDef>();

            byte[] msg = serializer.PackSingleObject(BuyGoldReq);
            _gsProxy.notifyMP(BaseMessage.LOBBY_SHOP_EXCHANGE_COIN_REQ_MSG, msg);
            Debug.Log("OnClickBuyGold Success:  sShopID:" + sShopID + "     sItemIndex:" + sItemIndex);
        }
        /// <summary>
        /// Serializes the specified value.
        /// </summary>
        /// <typeparam name="TObject">The type of the object.</typeparam>
        /// <param name="value">The value.</param>
        /// <returns>System.Byte[].</returns>
        public byte[] Serialize <TObject>(TObject value)
        {
            var responseSerializer = SerializerCache.GetOrAdd(typeof(TObject), MessagePackSerializer.Get <TObject>()) as MessagePackSerializer <TObject>;

            if (responseSerializer != null)
            {
                return(responseSerializer.PackSingleObject(value));
            }

            return(new byte[0]);
        }
Beispiel #22
0
        public T DeserializeObject <T>(string content)
        {
            var serializer = MessagePackSerializer.Get <T>();
            T   subject;

            using (var ms = new MemoryStream(Convert.FromBase64String(content)))
            {
                ms.Position = 0;
                subject     = serializer.Unpack(ms);
            }
            return(subject);
        }
Beispiel #23
0
        public object DeserializeObject(string content, Type type)
        {
            var    serializer = MessagePackSerializer.Get(type);
            object subject;

            using (var ms = new MemoryStream(Convert.FromBase64String(content)))
            {
                ms.Position = 0;
                subject     = serializer.Unpack(ms);
            }
            return(subject);
        }
Beispiel #24
0
        public void LobbyLoginReqDef(int userId, string token)
        {
            BaseMessage.LobbyLoginReqDef LobbyLoginReqDef = new BaseMessage.LobbyLoginReqDef();

            LobbyLoginReqDef.userId = userId;
            LobbyLoginReqDef.token  = token;//"2e4f847b-558"

            var serializer = MessagePackSerializer.Get <BaseMessage.LobbyLoginReqDef>();

            byte[] msg = serializer.PackSingleObject(LobbyLoginReqDef);
            _gsProxy.notifyMP(BaseMessage.LOBBY_LOGIN_REQ_MSG, msg);
        }
Beispiel #25
0
        //陈哲不需要用到,只作为测试数据是否有正常返回
        private void Mc_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            // 1. Create serializer instance.
            var serializer = MessagePackSerializer.Get <result>(new SerializationContext()
            {
                SerializationMethod = SerializationMethod.Map
            });
            // 3. Deserialize object from the specified stream.
            var deserializedObject = serializer.Unpack(new MemoryStream(e.Message));

            Console.WriteLine("收到消息:" + Newtonsoft.Json.JsonConvert.SerializeObject(deserializedObject));
        }
Beispiel #26
0
        /// <summary>
        /// Deserializes the specified value.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value.</param>
        /// <returns>T.</returns>
        public T Deserialize <T> (RedisValue value)
        {
            if (value.IsNull)
            {
                return(default(T));
            }
            var serializer = MessagePackSerializer.Get <T> ();

            using (var stream = new MemoryStream(value)) {
                return(serializer.Unpack(stream));
            }
        }
Beispiel #27
0
        /// <summary>
        /// The pack.
        /// </summary>
        /// <param name="mb">
        /// The mb.
        /// </param>
        /// <returns>
        /// The <see cref="byte[]"/>.
        /// </returns>
        public static byte[] Pack(BaseMessage mb)
        {
            var dm = new DynamicMessage();

            dm.DataObject = mb;
            if (serializer == null)
            {
                serializer = MessagePackSerializer.Get <DynamicMessage>();
            }

            return(serializer.PackSingleObject(dm));
        }
Beispiel #28
0
        public void Connect()
        {
            _ws.Connect();

            var serializer = MessagePackSerializer.Get <SayHello>();
            var frame      = serializer.PackSingleObject(new SayHello
            {
                Name = Name
            });

            _ws.Send(frame);
        }
        public void TestSerialize_OnNotNullResult_ReturnValueDataIsSet_ErrorDataIsNil()
        {
            TestCore((target, transport) =>
            {
                target.MessageId = 123;
                target.Serialize("Test", RpcErrorMessage.Success, MessagePackSerializer.Get <string>());

                Assert.That(Unpacking.UnpackObject(target.GetReturnValueData()).Value.Equals("Test"));
                Assert.That(Unpacking.UnpackObject(target.GetErrorData()).Value.Equals(MessagePackObject.Nil));
            }
                     );
        }
Beispiel #30
0
        // 对发送给服务端的数据进行打包
        public void rpcCall(string funcname, string parameters = null, RpcCallBackDelegate callback = null)
        {
            // generate protobuf msg
            var tmp = new NinjaMessage.Message
            {
                OpCode = NinjaMessage.OPCODE.RpcCall,
                Uid    = int.Parse(netProtocol.Node.uid)
            };

            tmp.Request         = new NinjaMessage.Request();
            tmp.Request.RpcFunc = funcname;

            // use msgpack to pack the parameters
            if (parameters != null)
            {
                string paramString = parameters;
                var    serializer  = MessagePackSerializer.Get <string>();
                using (var byteStream = new MemoryStream())
                {
                    serializer.Pack(byteStream, paramString);
                    byte[] tmpBytes = new byte[byteStream.Length];
                    int    iter     = 0;
                    byteStream.Seek(0, SeekOrigin.Begin);
                    StringBuilder myStringBuilder = new StringBuilder();
                    while (iter < tmpBytes.Length)
                    {
                        byte numIter  = (byte)(byteStream.ReadByte());
                        char tempChar = '\u0000';
                        tempChar += (char)numIter;
                        myStringBuilder.Append(tempChar);
                        tmpBytes[iter++] = numIter;
                    }
                    tmp.Request.RpcParams = Convert.ToBase64String(tmpBytes);
                }
            }

            // use protobuf to encode message
            byte[] protoMsg;
            using (var byteStream = new MemoryStream())
            {
                tmp.WriteTo(byteStream);
                protoMsg = new byte[byteStream.Length];
                int iter = 0;
                byteStream.Seek(0, SeekOrigin.Begin);
                while (iter < protoMsg.Length)
                {
                    protoMsg[iter++] = (byte)(byteStream.ReadByte());
                }
            }

            // DebugLogger.Debug(tmp.Request.RpcParams);
            SendMessage(protoMsg, "RPC_CALL", callback);
        }