/// <summary> /// Gets executed if BeginRead() has red some data /// </summary> /// <param name="ar">Async Result</param> private void OutputCallback(IAsyncResult ar) { AsyncState state = (AsyncState)ar.AsyncState; int count = state.Stream.BaseStream.EndRead(ar); if (count > 0) { int readCount = 0; while (count > readCount) { var data = Unpacking.UnpackObject(state.Buffer, readCount); readCount += data.ReadCount; if (!data.Value.IsArray) { Debugger.Break(); } var dataList = data.Value.AsList().Select(x => new MessagePackObject(x)).ToList(); // Response message has 4 items in the array if (dataList.Count == 4) { var type = (MessageType)dataList[0].AsInteger(); if (type != MessageType.Response) { Debugger.Break(); } var msgId = dataList[1].AsInteger(); var err = dataList[2]; var res = dataList[3]; _tcs[msgId].SetResult(new[] { err, res }); } // Notification message has 3 items in the array else if (dataList.Count == 3) { var type = (MessageType)dataList[0].AsInteger(); if (type != MessageType.Notification) { Debugger.Break(); } var func = dataList[1].AsString(Encoding.Default); var res = dataList[2]; MsgPackNotificationEventArgs args = new MsgPackNotificationEventArgs { Method = func, Params = res }; OnNotificationReceived(args); } else { Debugger.Break(); } } Array.Clear(state.Buffer, 0, state.Buffer.Length); _standardOutput.BaseStream.BeginRead( _outputBuffer, 0, _outputBuffer.Length, _outputReady, _outputState ); } }
void ParseMessage(byte[] recv) { UnpackingResult <MessagePackObject> raw = Unpacking.UnpackObject(recv); var message = raw.Value.AsList(); var code = message [0].AsInt32(); // Parse roomId or roomName Room room = null; int roomIdInt32 = 0; string roomId = "0"; string roomName = null; try { roomIdInt32 = message[1].AsInt32(); roomId = roomIdInt32.ToString(); } catch (InvalidOperationException) { try { roomName = message[1].AsString(); } catch (InvalidOperationException) {} } if (code == Protocol.USER_ID) { this.id = message [1].AsString(); this.OnOpen.Invoke(this, EventArgs.Empty); } else if (code == Protocol.JOIN_ROOM) { roomName = message[2].AsString(); if (this.rooms.ContainsKey(roomName)) { this.rooms [roomId] = this.rooms [roomName]; this.rooms.Remove(roomName); } room = this.rooms [roomId]; room.id = roomIdInt32; } else if (code == Protocol.JOIN_ERROR) { room = this.rooms [roomName]; MessageEventArgs error = new MessageEventArgs(room, message); room.EmitError(error); this.OnError.Invoke(this, error); this.rooms.Remove(roomName); } else if (code == Protocol.LEAVE_ROOM) { room = this.rooms [roomId]; room.Leave(false); } else if (code == Protocol.ROOM_STATE) { var state = message [2]; var remoteCurrentTime = message [3].AsInt32(); var remoteElapsedTime = message [4].AsInt32(); room = this.rooms [roomId]; // JToken.Parse (message [2].ToString ()) room.SetState(state, remoteCurrentTime, remoteElapsedTime); } else if (code == Protocol.ROOM_STATE_PATCH) { room = this.rooms [roomId]; IList <MessagePackObject> patchBytes = message [2].AsList(); byte[] patches = new byte[patchBytes.Count]; int idx = 0; foreach (MessagePackObject obj in patchBytes) { patches[idx] = obj.AsByte(); idx++; } room.ApplyPatch(patches); } else if (code == Protocol.ROOM_DATA) { room = this.rooms [roomId]; room.ReceiveData(message [2]); this.OnMessage.Invoke(this, new MessageEventArgs(room, message[2])); } }
public void SerializeThenDeserialize() { // They are object for just description. var targetObject = new PhotoEntry // See Sample01_BasicUsage.cs { Id = 123, Title = "My photo", Date = DateTime.Now, Image = new byte[] { 1, 2, 3, 4 }, Comment = "This is test object to be serialize/deserialize using MsgPack." }; targetObject.Tags.Add("Sample"); targetObject.Tags.Add("Excellent"); var stream = new MemoryStream(); // Set using Map instead of Array to serialize complex object. See Sample03 for details. var context = new SerializationContext(); context.SerializationMethod = SerializationMethod.Map; // You can use default context if you want to use map in all serializations which use default context. // SerializationContext.Default.SerializationMethod = SerializationMethod.Map; // 1. Create serializer instance. var serializer = MessagePackSerializer.Get <PhotoEntry>(context); // 2. Serialize object to the specified stream. serializer.Pack(stream, targetObject); // Set position to head of the stream to demonstrate deserialization. stream.Position = 0; // 3. Unpack MessagePackObject to get raw representation. var rawObject = Unpacking.UnpackObject(stream); // 3-b. You can read MPO tree via Unpacker // var unpacker = Unpacker.Create( stream ); // 3-c. Or, you can get it from serializer directly. // var rawObject = MessagePackSerializer.UnpackMessagePackObject( stream ); // Check its type Debug.WriteLine("Is array? {0}", rawObject.IsArray); // IsList is alias Debug.WriteLine("Is map? {0}", rawObject.IsMap); // IsDictionary is alias Debug.WriteLine("Type: {0}", rawObject.UnderlyingType); // Gets serialized fields. // Note: When the object was serialized as array instead of map, use index instead. var asDictionary = rawObject.AsDictionary(); Debug.WriteLine("Id : {0}({1})", asDictionary["Id"], asDictionary["Id"].UnderlyingType); // String is encoded as utf-8 by default. Debug.WriteLine("Title : {0}({1})", asDictionary["Title"], asDictionary["Title"].UnderlyingType); // Non-primitive is serialized as complex type or encoded primitive type. // DateTimeOffset is encoded as array[2]{ticks,offset} Debug.WriteLine("Date : {0}({1})", asDictionary["Date"], asDictionary["Date"].UnderlyingType); // byte[] is byte[], as you know. Debug.WriteLine("Image : {0}({1})", asDictionary["Image"], asDictionary["Image"].UnderlyingType); // 4. Now MessagePackSerializer handle MessagePackObject directly. var mpo = serializer.ToMessagePackObject(targetObject); var asDictionary2 = mpo.AsDictionary(); Debug.WriteLine("---- ToMessagePackObject ----"); Debug.WriteLine("Id : {0}({1})", asDictionary2["Id"], asDictionary2["Id"].UnderlyingType); Debug.WriteLine("Title : {0}({1})", asDictionary2["Title"], asDictionary2["Title"].UnderlyingType); Debug.WriteLine("Date : {0}({1})", asDictionary2["Date"], asDictionary2["Date"].UnderlyingType); Debug.WriteLine("Image : {0}({1})", asDictionary2["Image"], asDictionary2["Image"].UnderlyingType); // reversing var targetObject2 = serializer.FromMessagePackObject(mpo); Debug.WriteLine("---- FromMessagePackObject ----"); Debug.WriteLine("Id : {0}", targetObject2.Id); Debug.WriteLine("Title : {0}", targetObject2.Title); Debug.WriteLine("Date : {0}", targetObject2.Date); Debug.WriteLine("Image : {0}", Convert.ToBase64String(targetObject2.Image)); }
public void TestGetServiceInvoker_ReturnsValidInvoker_NonErrorCase() { using (var target = new ServiceInvokerGenerator(true)) { var arg1 = Guid.NewGuid().ToString(); var arg2 = Environment.TickCount; var returnValue = true; this.TestGetServiceInvokerCore <string, int, bool>( (sender, e) => { Assert.That(e.Arguments.Length, Is.EqualTo(2)); Assert.That(e.Arguments[0], Is.EqualTo(arg1)); Assert.That(e.Arguments[1], Is.EqualTo(arg2)); e.ReturnValue = returnValue; }, new RpcServerConfiguration() { IsDebugMode = true }, arg1, arg2, responseContext => { Assert.That(Unpacking.UnpackObject(responseContext.GetErrorData()).Value.IsNil, Unpacking.UnpackObject(responseContext.GetErrorData()).Value.ToString()); Assert.That(Unpacking.UnpackObject(responseContext.GetReturnValueData()).Value.AsBoolean()); } ); } }
public void TestGetServiceInvoker_ReturnsValidInvoker_ErrorCase_IsNotDebugMode_NotRpcError_DefaultMessage() { using (var target = new ServiceInvokerGenerator(true)) { var arg1 = Guid.NewGuid().ToString(); var arg2 = Environment.TickCount; var rpcError = RpcError.CallError; this.TestGetServiceInvokerCore <string, int, bool>( (sender, e) => { Assert.That(e.Arguments.Length, Is.EqualTo(2)); Assert.That(e.Arguments[0], Is.EqualTo(arg1)); Assert.That(e.Arguments[1], Is.EqualTo(arg2)); e.Exception = new Exception(Guid.NewGuid().ToString()); }, new RpcServerConfiguration() { IsDebugMode = false }, arg1, arg2, responseContext => { Assert.That(Unpacking.UnpackObject(responseContext.GetErrorData()).Value.Equals(rpcError.Identifier), "{0}!={1}", Unpacking.UnpackObject(responseContext.GetErrorData()).Value, rpcError.Identifier); var exception = new RpcException(rpcError, Unpacking.UnpackObject(responseContext.GetReturnValueData()).Value); Assert.That(exception.RpcError.Identifier, Is.EqualTo(rpcError.Identifier)); Assert.That(exception.RpcError.ErrorCode, Is.EqualTo(rpcError.ErrorCode)); Assert.That(exception.Message, Is.EqualTo(rpcError.DefaultMessageInvariant)); Assert.That(exception.DebugInformation, Is.Empty); } ); } }
public void TestUri() { TestCore(new Uri("http://www.example.com"), stream => new Uri(Unpacking.UnpackString(stream)), null); }
public void TestEnum() { TestCore(DayOfWeek.Sunday, stream => ( DayOfWeek )Enum.Parse(typeof(DayOfWeek), Unpacking.UnpackString(stream)), (x, y) => x == y); }
public void TestInt64() { TestCore(Int32.MaxValue + 1L, stream => Unpacking.UnpackInt64(stream), null); }
public void TestString() { TestCore("abc", stream => Unpacking.UnpackString(stream), null); }
public void TestInt32() { TestCore(1, stream => Unpacking.UnpackInt32(stream), null); }
private void TestEchoRequestCore(ref bool isOk, ManualResetEventSlim waitHandle, string message) { using (var client = new TcpClient()) { client.Connect(new IPEndPoint(IPAddress.Loopback, CallbackServer.PortNumber)); var now = MessagePackConvert.FromDateTime(DateTime.Now); using (var stream = client.GetStream()) using (var packer = Packer.Create(stream)) { this._trace.TraceInformation("---- Client sending request ----"); packer.PackArrayHeader(4); packer.Pack(0); packer.Pack(123); packer.Pack("Echo"); packer.PackArrayHeader(2); packer.Pack(message); packer.Pack(now); this._trace.TraceInformation("---- Client sent request ----"); if (Debugger.IsAttached) { waitHandle.Wait(); } else { Assert.That(waitHandle.Wait(TimeSpan.FromSeconds(3))); } this._trace.TraceInformation("---- Client receiving response ----"); var result = Unpacking.UnpackObject(stream); Assert.That(result.IsArray); var array = result.AsList(); Assert.That(array.Count, Is.EqualTo(4)); Assert.That( array[0] == 1, String.Format( CultureInfo.CurrentCulture, "Expected: {1}{0}Actual : {2}", Environment.NewLine, 1, array[0].ToString())); Assert.That( array[1] == 123, String.Format( CultureInfo.CurrentCulture, "Expected: {1}{0}Actual : {2}", Environment.NewLine, 123, array[1].ToString())); Assert.That( array[2] == MessagePackObject.Nil, String.Format( CultureInfo.CurrentCulture, "Expected: {1}{0}Actual : {2}", Environment.NewLine, MessagePackObject.Nil, array[2].ToString())); Assert.That(array[3].IsArray, array[3].ToString()); var returnValue = array[3].AsList(); Assert.That(returnValue.Count, Is.EqualTo(2)); Assert.That( returnValue[0] == message, String.Format( CultureInfo.CurrentCulture, "Expected: {1}{0}Actual : {2}", Environment.NewLine, message, returnValue[0].ToString())); Assert.That( returnValue[1] == now, String.Format( CultureInfo.CurrentCulture, "Expected: {1}{0}Actual : {2}", Environment.NewLine, now, returnValue[1].ToString())); this._trace.TraceInformation("---- Client received response ----"); } } }
/// <summary> /// Unpacks <see cref="RpcErrorMessage"/> from stream in the specified context. /// </summary> /// <param name="context"><see cref="ClientResponseContext"/> which stores serialized error.</param> /// <returns>An unpacked <see cref="RpcErrorMessage"/>.</returns> internal static RpcErrorMessage UnpackError(ClientResponseContext context) { Contract.Assert(context != null); Contract.Assert(context.ErrorBuffer != null); Contract.Assert(context.ErrorBuffer.Length > 0); Contract.Assert(context.ResultBuffer != null); Contract.Assert(context.ResultBuffer.Length > 0); MessagePackObject error; try { error = Unpacking.UnpackObject(context.ErrorBuffer); } catch (UnpackException) { error = new MessagePackObject(context.ErrorBuffer.GetBuffer().SelectMany(segment => segment.AsEnumerable()).ToArray()); } if (error.IsNil) { return(RpcErrorMessage.Success); } bool isUnknown = false; RpcError errorIdentifier; if (error.IsTypeOf <string>().GetValueOrDefault()) { var asString = error.AsString(); errorIdentifier = RpcError.FromIdentifier(asString, null); // Check if the error is truely Unexpected error. isUnknown = errorIdentifier.ErrorCode == RpcError.Unexpected.ErrorCode && asString != RpcError.Unexpected.Identifier; } else if (error.IsTypeOf <int>().GetValueOrDefault()) { errorIdentifier = RpcError.FromIdentifier(null, error.AsInt32()); } else { errorIdentifier = RpcError.Unexpected; isUnknown = true; } MessagePackObject detail; if (context.ResultBuffer.Length == 0) { detail = MessagePackObject.Nil; } else { try { detail = Unpacking.UnpackObject(context.ResultBuffer); } catch (UnpackException) { detail = new MessagePackObject(context.ResultBuffer.GetBuffer().SelectMany(segment => segment.AsEnumerable()).ToArray()); } } if (isUnknown) { // Unknown error, the error should contain original Error field as message. if (detail.IsNil) { return(new RpcErrorMessage(errorIdentifier, error.AsString(), null)); } else { var details = new MessagePackObjectDictionary(2); details[RpcException.MessageKeyUtf8] = error; details[RpcException.DebugInformationKeyUtf8] = detail; return(new RpcErrorMessage(errorIdentifier, new MessagePackObject(details, true))); } } else { return(new RpcErrorMessage(errorIdentifier, detail)); } }
public async Task <Dictionary <string, object> > Execute(string method, params object[] args) { if (string.IsNullOrEmpty(_host)) { throw new Exception("Host null or empty"); } if (method != "auth.login" && string.IsNullOrEmpty(_token)) { throw new Exception("Not authenticated."); } ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => { return(true); }; //dis be bad, no ssl check HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_host); request.ContentType = "binary/message-pack"; request.Method = "POST"; request.KeepAlive = true; Stream requestStream = null; try{ requestStream = request.GetRequestStream(); } catch (Exception ex) { Console.WriteLine(ex); } var msgpackWriter = Packer.Create(requestStream); msgpackWriter.PackArrayHeader(args.Length + 1 + (string.IsNullOrEmpty(_token) ? 0 : 1)); msgpackWriter.PackString(method); if (!string.IsNullOrEmpty(_token) && method != "auth.login") { msgpackWriter.Pack(_token); } foreach (object arg in args) { Pack(msgpackWriter, arg); } requestStream.Close(); var buffer = new byte[4096]; var mstream = new MemoryStream(); try { using WebResponse response = request.GetResponse(); await using Stream rstream = response.GetResponseStream(); int count = 0; do { count = rstream.Read(buffer, 0, buffer.Length); mstream.Write(buffer, 0, count); } while (count != 0); } catch (WebException ex) { if (ex.Response != null) { string res = string.Empty; using (StreamReader rdr = new StreamReader(ex.Response.GetResponseStream())) res = await rdr.ReadToEndAsync(); Console.WriteLine(res); } } mstream.Position = 0; var resp = Unpacking.UnpackObject(mstream).AsDictionary(); var returnDictionary = TypifyDictionary(resp); return(returnDictionary); }
private static void TestSendReceiveRequestCore(IPEndPoint endPoint, int count, CountdownEvent latch) { using (var tcpClient = new TcpClient(AddressFamily.InterNetwork)) { tcpClient.Connect(endPoint); using (var stream = tcpClient.GetStream()) { for (int i = 0; i < count; i++) { if (latch != null) { latch.Reset(); } var ids = Enumerable.Repeat(0, latch == null ? 1 : latch.InitialCount).Select(_ => Guid.NewGuid().ToString()).ToArray(); if (!Task.WaitAll( ids.Select( id => Task.Factory.StartNew( _ => { using (var buffer = new MemoryStream()) { using (var packer = Packer.Create(buffer, false)) { PackRequest(packer, id); } buffer.Position = 0; if (latch != null) { latch.Signal(); if (!latch.Wait(Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds)) { throw new TimeoutException(); } } // send buffer.CopyTo(stream); } }, id ) ).ToArray(), Debugger.IsAttached ? Timeout.Infinite : TimeoutMilliseconds )) { throw new TimeoutException(); } // receive var result = Unpacking.UnpackArray(stream); AssertResponse(result, ids); } } } }