private static DsoChatPacket TryParseAmf(string rawXmlData, byte[] rawData) { if (rawXmlData.Contains(@"/onResult") == false || rawXmlData.Contains("\r\n\r\n") == false) { return(null); } // Skip after \r\n\r\n int p = rawXmlData.IndexOf("\r\n\r\n"); var amfBody = rawXmlData.Substring(p + 4); // Next \r\n denotes AMF start, i thinnk.. if (amfBody.Contains("\r\n")) { p = amfBody.IndexOf("\r\n"); amfBody = amfBody.Substring(p + 2); } var amfRawBody = TextEncoding.GetBytes(amfBody); using (var stream = new MemoryStream(amfRawBody)) { var deserializer = new AMFDeserializer(stream); var message = deserializer.ReadAMFMessage(); } return(null); }
public override void Invoke(AMFContext context) { AMFDeserializer deserializer = new AMFDeserializer(context.InputStream); deserializer.UseLegacyCollection = _useLegacyCollection; try { AMFMessage amfMessage = deserializer.ReadAMFMessage(); context.AMFMessage = amfMessage; context.MessageOutput = new MessageOutput(amfMessage.Version); if (deserializer.FailedAMFBodies.Length > 0) { AMFBody[] failedAMFBodies = deserializer.FailedAMFBodies; //Write out failed AMFBodies for (int i = 0; i < failedAMFBodies.Length; i++) { context.MessageOutput.AddBody(failedAMFBodies[i]); } } } catch { Dump(context.InputStream); throw; } }
/// <summary> /// 解析响应报文,把报文内容以amf对象的形式返回 /// </summary> /// <param name="response">响应报文</param> /// <returns>返回amf信息对象</returns> public static AMFMessage GetAMFMessage(this WebResponse response) { using (Stream Stream = response.GetResponseStream()) { using (AMFDeserializer AMFDeserializer = new AMFDeserializer(Stream)) { return(AMFDeserializer.ReadAMFMessage()); } } }
/// <summary> /// One of the two main entry points into the encoder. Called by WCF to decode a buffered byte array into a message. /// </summary> /// <param name="buffer">A <see cref="T:System.ArraySegment`1"/> of type <see cref="T:System.Byte"/> that provides the buffer from which the message is deserialized.</param> /// <param name="bufferManager">The <see cref="T:System.ServiceModel.Channels.BufferManager"/> that manages the buffer from which the message is deserialized.</param> /// <param name="contentType">The Multipurpose Internet Mail Extensions (MIME) message-level content-type.</param> /// <returns> /// The <see cref="T:System.ServiceModel.Channels.Message"/> that is read from the stream specified. /// </returns> public override Message ReadMessage(ArraySegment <byte> buffer, BufferManager bufferManager, string contentType) { MemoryStream memoryStream = new MemoryStream(buffer.Array, buffer.Offset, buffer.Count - buffer.Offset); AMFDeserializer amfDeserializer = new AMFDeserializer(memoryStream); AMFMessage amfMessage = amfDeserializer.ReadAMFMessage(); Message returnMessage = Message.CreateMessage(MessageVersion.None, null); returnMessage.Properties.Add("amf", amfMessage); return(returnMessage); }
/// <summary> /// 解析响应报文,把报文内容以字符串的形式返回 /// </summary> /// <param name="response">响应报文</param> /// <returns>返回报文内容字符串</returns> public static string GetText(this WebResponse response) { using (Stream stream = response.GetResponseStream()) { using (AMFDeserializer amfDeserializer = new AMFDeserializer(stream)) { AcknowledgeMessage msg = (AcknowledgeMessage)amfDeserializer.ReadAMFMessage().Bodies[0].Content; return(Convert.ToString(msg.body)); } } }
private void parse(string amf, string name) { byte[] bbb = StrToToHexByte(amf); AMFDeserializer ad = new AMFDeserializer(new MemoryStream(bbb)); AMFMessage message = ad.ReadAMFMessage(); string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(message); //Write that JSON to txt file File.WriteAllText(@"z:\temp\hotel\" + name + @".json", json); foreach (var body in message.Bodies) { object[] content = body.Content as object[]; RemotingMessage rm = content[0] as RemotingMessage; rm.messageId = Guid.NewGuid().ToString("D"); object[] bodys = rm.body as object[]; ASObject ab = bodys[2] as ASObject; ASObject masterBase = ab["masterBase"] as ASObject; masterBase["dep"] = DateTime.Now; masterBase["arr"] = DateTime.Now; masterBase["rsvMan"] = "马一一"; masterBase["cutoffDate"] = DateTime.Now; ASObject masterGuest = ab["masterGuest"] as ASObject; masterGuest["name"] = "马一一"; masterGuest["name2"] = "Ma Yi Yi"; masterGuest["sex"] = "1"; ArrayCollection rsvSrcList = ab["rsvSrcList"] as ArrayCollection; ASObject rsvObject = rsvSrcList[0] as ASObject; rsvObject["arrDate"] = DateTime.Now; rsvObject["depDate"] = DateTime.Now; rsvObject["rsvArrDate"] = DateTime.Now; rsvObject["rsvDepDate"] = DateTime.Now; rsvObject["negoRate"] = 268; rsvObject["oldRate"] = 268; rsvObject["realRate"] = 268; rsvObject["rackRate"] = 268; } }
public override void Invoke(AMFContext context) { AMFDeserializer deserializer = new AMFDeserializer(context.InputStream); deserializer.UseLegacyCollection = _useLegacyCollection; try { AMFMessage amfMessage = deserializer.ReadAMFMessage(); context.AMFMessage = amfMessage; context.MessageOutput = new MessageOutput(amfMessage.Version); if (deserializer.FailedAMFBodies.Length > 0) { AMFBody[] failedAMFBodies = deserializer.FailedAMFBodies; //Write out failed AMFBodies for (int i = 0; i < failedAMFBodies.Length; i++) context.MessageOutput.AddBody(failedAMFBodies[i]); } } catch { Dump(context.InputStream); throw; } }
/// <summary> /// 获取当前的村委会清单 /// </summary> /// <param name="cookie"></param> /// <param name="responseNo"></param> /// <returns></returns> public DataSet GetSysCommittee(string cookie, string responseNo) { DataSet dtUploadSetRow = new DataSet(); ManagerBase mb = new ManagerBase(SendType.Query); byte[] byteSend = GetNode(responseNo); string sendHeader = CommonExtensions.GetSendHeader(cookie, byteSend.Length).ToString(); mb.SendMessage(cookie, byteSend, sendHeader); AMFDeserializer ad = new AMFDeserializer(new MemoryStream(mb.socketReceiveData)); AMFMessage timeMessage = ad.ReadAMFMessage(); mb.socketReceiveData = null; if (timeMessage.BodyCount == 0 || timeMessage.Bodies.FirstOrDefault().Content is FluorineFx.Messaging.Messages.ErrorMessage) { CommonExtensions.WriteLog("不存在"); return(dtUploadSetRow); } var content = (AcknowledgeMessage)timeMessage.Bodies.FirstOrDefault().Content; // node 字符串 /* * <node id='3064' name='中亚南路街道办事处' level='4' levelCN='乡镇' code='650104014' isLoad='true' isBranch='true'> * <node id='3718' name='团结新村社区居委会' level='5' levelCN='村' code='650104014007' isLoad='false' ></node> * <node id='3721' name='铁路花园社区居委会' level='5' levelCN='村' code='650104014010' isLoad='false' ></node> * </node> */ var strNodes = content.body.ToString(); using (StringReader xmlSR = new StringReader(strNodes)) { dtUploadSetRow.ReadXml(xmlSR); } return(dtUploadSetRow); }
public override void Invoke(AMFContext context) { AMFDeserializer deserializer = new AMFDeserializer(context.InputStream) { UseLegacyCollection = this._useLegacyCollection }; AMFMessage message = deserializer.ReadAMFMessage(); context.AMFMessage = message; context.MessageOutput = new MessageOutput(message.Version); if (deserializer.FailedAMFBodies.Length > 0) { AMFBody[] failedAMFBodies = deserializer.FailedAMFBodies; for (int i = 0; i < failedAMFBodies.Length; i++) { context.MessageOutput.AddBody(failedAMFBodies[i]); } } }
public override Task Invoke(AMFContext context) { AMFDeserializer deserializer = new AMFDeserializer(context.InputStream); deserializer.UseLegacyCollection = _useLegacyCollection; AMFMessage amfMessage = deserializer.ReadAMFMessage(); context.AMFMessage = amfMessage; context.MessageOutput = new MessageOutput(amfMessage.Version); if (deserializer.FailedAMFBodies.Length > 0) { AMFBody[] failedAMFBodies = deserializer.FailedAMFBodies; //Write out failed AMFBodies for (int i = 0; i < failedAMFBodies.Length; i++) { context.MessageOutput.AddBody(failedAMFBodies[i]); } } return(Task.FromResult <object>(null)); }
private void BeginResponseFlexCall(IAsyncResult ar) { try { AmfRequestData amfRequestData = ar.AsyncState as AmfRequestData; if (amfRequestData != null) { HttpWebResponse response = (HttpWebResponse)amfRequestData.Request.EndGetResponse(ar); if (response != null) { //Get response and deserialize Stream responseStream = response.GetResponseStream(); if (responseStream != null) { AMFDeserializer amfDeserializer = new AMFDeserializer(responseStream); AMFMessage responseMessage = amfDeserializer.ReadAMFMessage(); AMFBody responseBody = responseMessage.GetBodyAt(0); for (int i = 0; i < responseMessage.HeaderCount; i++) { AMFHeader header = responseMessage.GetHeaderAt(i); if (header.Name == AMFHeader.RequestPersistentHeader) _netConnection.AddHeader(header.Name, header.MustUnderstand, header.Content); } object message = responseBody.Content; if (message is ErrorMessage) { /* ASObject status = new ASObject(); status["level"] = "error"; status["code"] = "NetConnection.Call.Failed"; status["description"] = (result as ErrorMessage).faultString; status["details"] = result; _netConnection.RaiseNetStatus(status); */ if (amfRequestData.Call != null) { PendingCall call = amfRequestData.Call; call.Result = message; call.Status = Messaging.Rtmp.Service.Call.STATUS_INVOCATION_EXCEPTION; amfRequestData.Callback.ResultReceived(call); } if (amfRequestData.Responder != null) { StatusFunction statusFunction = amfRequestData.Responder.GetType().GetProperty("Status").GetValue(amfRequestData.Responder, null) as StatusFunction; if (statusFunction != null) statusFunction(new Fault(message as ErrorMessage)); } } else if (message is AcknowledgeMessage) { AcknowledgeMessage ack = message as AcknowledgeMessage; if (_netConnection.ClientId == null && ack.HeaderExists(MessageBase.FlexClientIdHeader)) _netConnection.SetClientId(ack.GetHeader(MessageBase.FlexClientIdHeader) as string); if (amfRequestData.Call != null) { PendingCall call = amfRequestData.Call; call.Result = ack.body; call.Status = Messaging.Rtmp.Service.Call.STATUS_SUCCESS_RESULT; amfRequestData.Callback.ResultReceived(call); } if (amfRequestData.Responder != null) { Delegate resultFunction = amfRequestData.Responder.GetType().GetProperty("Result").GetValue(amfRequestData.Responder, null) as Delegate; if (resultFunction != null) { ParameterInfo[] arguments = resultFunction.Method.GetParameters(); object result = TypeHelper.ChangeType(ack.body, arguments[0].ParameterType); resultFunction.DynamicInvoke(result); } } } } else _netConnection.RaiseNetStatus("Could not aquire ResponseStream"); } else _netConnection.RaiseNetStatus("Could not aquire HttpWebResponse"); } } catch (Exception ex) { _netConnection.RaiseNetStatus(ex); } }
private void BeginResponseFlashCall(IAsyncResult ar) { try { AmfRequestData amfRequestData = ar.AsyncState as AmfRequestData; if (amfRequestData != null) { HttpWebResponse response = (HttpWebResponse)amfRequestData.Request.EndGetResponse(ar); if (response != null) { //Get response and deserialize Stream responseStream = response.GetResponseStream(); if (responseStream != null) { AMFDeserializer amfDeserializer = new AMFDeserializer(responseStream); AMFMessage responseMessage = amfDeserializer.ReadAMFMessage(); AMFBody responseBody = responseMessage.GetBodyAt(0); for (int i = 0; i < responseMessage.HeaderCount; i++) { AMFHeader header = responseMessage.GetHeaderAt(i); if (header.Name == AMFHeader.RequestPersistentHeader) _netConnection.AddHeader(header.Name, header.MustUnderstand, header.Content); } if (amfRequestData.Call != null) { PendingCall call = amfRequestData.Call; call.Result = responseBody.Content; call.Status = responseBody.Target.EndsWith(AMFBody.OnStatus) ? Messaging.Rtmp.Service.Call.STATUS_INVOCATION_EXCEPTION : Messaging.Rtmp.Service.Call.STATUS_SUCCESS_RESULT; amfRequestData.Callback.ResultReceived(call); } if (amfRequestData.Responder != null) { if (responseBody.Target.EndsWith(AMFBody.OnStatus)) { StatusFunction statusFunction = amfRequestData.Responder.GetType().GetProperty("Status").GetValue(amfRequestData.Responder, null) as StatusFunction; if (statusFunction != null) statusFunction(new Fault(responseBody.Content)); } else { Delegate resultFunction = amfRequestData.Responder.GetType().GetProperty("Result").GetValue(amfRequestData.Responder, null) as Delegate; if (resultFunction != null) { ParameterInfo[] arguments = resultFunction.Method.GetParameters(); object result = TypeHelper.ChangeType(responseBody.Content, arguments[0].ParameterType); resultFunction.DynamicInvoke(result); } } } } else _netConnection.RaiseNetStatus("Could not aquire ResponseStream"); } else _netConnection.RaiseNetStatus("Could not aquire HttpWebResponse"); } } catch (Exception ex) { _netConnection.RaiseNetStatus(ex); } }
private static DsoChatPacket TryParseAmf(string rawXmlData, byte[] rawData) { if (rawXmlData.Contains(@"/onResult") == false || rawXmlData.Contains("\r\n\r\n") == false) { return null; } // Skip after \r\n\r\n int p = rawXmlData.IndexOf("\r\n\r\n"); var amfBody = rawXmlData.Substring(p + 4); // Next \r\n denotes AMF start, i thinnk.. if (amfBody.Contains("\r\n")) { p = amfBody.IndexOf("\r\n"); amfBody = amfBody.Substring(p + 2); } var amfRawBody = TextEncoding.GetBytes(amfBody); using (var stream = new MemoryStream(amfRawBody)) { var deserializer = new AMFDeserializer(stream); var message = deserializer.ReadAMFMessage(); } return null; }
/// <summary> /// Десериализует буфер данных в объект AMF. /// </summary> /// <typeparam name="T">Тип десериализуемого объекта.</typeparam> /// <param name="sourceBuffer">Исходный буфер данных объекта.</param> /// <returns></returns> public static T DeserializeFromAmf <T>(this byte[] sourceBuffer) where T : class { using (MemoryStream memoryStream = new MemoryStream(sourceBuffer)) // Открываем поток для чтения данных из буфера. using (AMFDeserializer amfDeserializer = new AMFDeserializer(memoryStream)) // Инициализируем десериализатор для AMF. { AMFMessage amfMessage = amfDeserializer.ReadAMFMessage(); // Получем сообщение AMF. AMFBody amfBody = amfMessage.GetBodyAt(0); // Получаем body из сообщения AMF. object amfObject = amfBody.Content; // Получаем объект из body AMF. Type amfObjectType = amfObject.GetType(); // Получаем метаданные типа объекта AMF. // Формируем запрос на получение всей коллекции нужных нам типов с заданными атрибутами. IEnumerable <Type> types = from type in Assembly.GetExecutingAssembly().GetTypes() where Attribute.IsDefined(type, typeof(AmfObjectAttribute)) select type; Type currentType = null; // Определяем текущий тип объекта из нашей сборки. // Проходим по всем найденным типам с нашим атрибутом. foreach (Type type in types) { AmfObjectAttribute attribute = type.GetAttribute <AmfObjectAttribute>(); // Получаем наш атрибут. if (attribute == null || attribute.Name != amfObjectType.FullName) { continue; // Если в атрибуте задано другое имя - пропускаем итерацию. } currentType = type; // Иначе сохраняем текущий тип объекта. break; } if (currentType == null) { return(default(T)); // Если тип не найден - возвращаем null. } object targetObject = Activator.CreateInstance(currentType); // Создаём инстанс нашего типа. // Анализируем все свойства нашего класса. foreach (PropertyInfo propertyInfo in currentType.GetProperties()) { AmfMemberAttribute attribute = propertyInfo.GetAttribute <AmfMemberAttribute>(); // Получаем наш кастомный атрибут. if (attribute == null) { continue; // Если атрибут не задан - пропускаем. } propertyInfo.SetValue(targetObject, amfObjectType.GetProperty(attribute.Name).GetValue(amfObject, null), null); // Получаем значение свойства у десериализуемого объекта и сохраняем его в свойстве нашего объекта. } // Анализируем все поля нашего класса. foreach (FieldInfo fieldInfo in currentType.GetFields()) { AmfMemberAttribute attribute = fieldInfo.GetAttribute <AmfMemberAttribute>(); // Получаем наш кастомный атрибут. if (attribute == null) { continue; // Если атрибут не задан - пропускаем. } fieldInfo.SetValue(targetObject, amfObjectType.GetField(attribute.Name).GetValue(amfObject)); // Получаем значение поля у десериализуемого объекта и сохраняем его в поле нашего объекта. } return(targetObject as T); // Приводит к типу T и возвращает текущий объект. } }