/// <summary> /// 发送基于x-amf3的http请求 /// </summary> /// <param name="requestUrl">请求url</param> /// <param name="amfMessage">amf3的报文体</param> /// <param name="cookieContainer">请求的cookie</param> public static WebResponse Amf3RequestHelper(string requestUrl, AMFMessage amfMessage, CookieContainer cookieContainer = null) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(requestUrl); req.Method = "POST"; req.ContentType = "application/x-amf"; req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"; req.CookieContainer = cookieContainer; req.LoadConfig(requestUrl); using (Stream stream = req.GetRequestStream()) { using (AMFSerializer AMFSerializer = new AMFSerializer(stream)) { AMFSerializer.WriteMessage(amfMessage); } } try { return(req.GetResponse()); } catch (WebException ex) { if (ex.Message.Contains("502")) { Console.WriteLine("连接远程服务器时发生错误!", ex); throw new Exception("地址:" + requestUrl + "连接失败,(ERROR:-1)"); } throw ex; } }
/// <summary> /// One of the two main entry points into the encoder. Called by WCF to write a message of less than a specified size to a byte array buffer at the specified offset. /// </summary> /// <param name="message">The <see cref="T:System.ServiceModel.Channels.Message"/> to write to the message buffer.</param> /// <param name="maxMessageSize">The maximum message size that can be written.</param> /// <param name="bufferManager">The <see cref="T:System.ServiceModel.Channels.BufferManager"/> that manages the buffer to which the message is written.</param> /// <param name="messageOffset">The offset of the segment that begins from the start of the byte array that provides the buffer.</param> /// <returns> /// A <see cref="T:System.ArraySegment`1"/> of type byte that provides the buffer to which the message is serialized. /// </returns> public override ArraySegment <byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset) { MemoryStream memoryStream = new MemoryStream(); AMFMessage amfMessage = message.Properties["amf"] as AMFMessage; AMFSerializer serializer = new AMFSerializer(memoryStream); serializer.WriteMessage(amfMessage); serializer.Flush(); // To avoid a buffer copy, we grab a reference to the stream's internal buffer. // The byte[] we receive may contain extra nulls after the actual data, due to the // buffer management mechanisms of the MemoryStream. Thus, to obtain the message's // length, we need to examine memoryStream.Position rather than messageBytes.Length. byte[] messageBytes = memoryStream.GetBuffer(); int messageLength = (int)memoryStream.Position; memoryStream.Close(); int totalLength = messageLength + messageOffset; byte[] finalBuffer = bufferManager.TakeBuffer(totalLength); Array.Copy(messageBytes, 0, finalBuffer, messageOffset, messageLength); ArraySegment <byte> byteArray = new ArraySegment <byte>(finalBuffer, messageOffset, messageLength); return(byteArray); }
public override void Invoke(AMFContext context) { AMFSerializer serializer = new AMFSerializer(context.OutputStream); serializer.UseLegacyCollection = _useLegacyCollection; serializer.UseLegacyThrowable = _useLegacyThrowable; serializer.WriteMessage(context.MessageOutput); serializer.Flush(); //Serialization/deserialization debugging //Note: this will not work correctly with optimizers (different ClassDefinitions from server and client) /* * MemoryStream ms = new MemoryStream(); * AMFSerializer testSerializer = new AMFSerializer(ms); * testSerializer.UseLegacyCollection = _useLegacyCollection; * testSerializer.UseLegacyThrowable = _useLegacyThrowable; * testSerializer.WriteMessage(context.MessageOutput); * testSerializer.Flush(); * ms.Position = 0; * AMFDeserializer testDeserializer = new AMFDeserializer(ms); * testDeserializer.UseLegacyCollection = _useLegacyCollection; * AMFMessage amfMessageOut = testDeserializer.ReadAMFMessage(); * ms.Position = 0; * byte[] buffer = ms.ToArray(); * context.OutputStream.Write(buffer, 0, buffer.Length); */ }
public override void Invoke(AMFContext context) { AMFSerializer serializer = new AMFSerializer(context.OutputStream); serializer.UseLegacyCollection = _useLegacyCollection; serializer.UseLegacyThrowable = _useLegacyThrowable; serializer.WriteMessage(context.MessageOutput); serializer.Flush(); //Serialization/deserialization debugging //Note: this will not work correctly with optimizers (different ClassDefinitions from server and client) /* MemoryStream ms = new MemoryStream(); AMFSerializer testSerializer = new AMFSerializer(ms); testSerializer.UseLegacyCollection = _useLegacyCollection; testSerializer.UseLegacyThrowable = _useLegacyThrowable; testSerializer.WriteMessage(context.MessageOutput); testSerializer.Flush(); ms.Position = 0; AMFDeserializer testDeserializer = new AMFDeserializer(ms); testDeserializer.UseLegacyCollection = _useLegacyCollection; AMFMessage amfMessageOut = testDeserializer.ReadAMFMessage(); ms.Position = 0; byte[] buffer = ms.ToArray(); context.OutputStream.Write(buffer, 0, buffer.Length); */ }
public override void Invoke(AMFContext context) { AMFSerializer serializer = new AMFSerializer(context.OutputStream); serializer.UseLegacyCollection = _useLegacyCollection; serializer.WriteMessage(context.MessageOutput); serializer.Flush(); }
public override Task Invoke(AMFContext context) { AMFSerializer serializer = new AMFSerializer(context.OutputStream); serializer.UseLegacyCollection = _useLegacyCollection; serializer.WriteMessage(context.MessageOutput); serializer.Flush(); return(Task.FromResult <object>(null)); }
//One of the two main entry points into the encoder. Called by WCF to encode a Message into a buffered byte array. public override ArraySegment <byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset) { MemoryStream memoryStream = new MemoryStream(); AMFMessage amfMessage = message.Properties["amf"] as AMFMessage; AMFSerializer serializer = new AMFSerializer(memoryStream); serializer.WriteMessage(amfMessage); serializer.Flush(); byte[] buffer = memoryStream.ToArray(); ArraySegment <byte> byteArray = new ArraySegment <byte>(buffer); return(byteArray); }
/// <summary> /// Сериализует объект в буффер AMF. /// </summary> /// <param name="sourceObject">Исходный объект.</param> /// <param name="version">Версия AMF.</param> /// <returns></returns> public static byte[] SerializeToAmf(this object sourceObject, ushort version) { using (MemoryStream memoryStream = new MemoryStream()) // Открываем поток для записи данных в буфер. using (AMFSerializer amfSerializer = new AMFSerializer(memoryStream)) // Инициализируем сериализатор для AMF. { AMFMessage amfMessage = new AMFMessage(version); // Создаём сообщение для передачи серверу с заданным номером версии AMF. AMFBody amfBody = new AMFBody(AMFBody.OnResult, null, GenerateType(sourceObject)); // Создаём тело для сообщения AMF. amfMessage.AddBody(amfBody); // Добавляем body для сообщения AMF. amfSerializer.WriteMessage(amfMessage); // Сериализуем сообщение. return(memoryStream.ToArray()); // Преобразовывает поток памяти в буфер и возвращает. } }
public byte[] LoadAmfMessageIntoBinMessage(AMFMessage message) { byte[] buffer = null; MemoryStream stream = new MemoryStream(); AMFSerializer amfSerializers = new AMFSerializer(stream); amfSerializers.WriteMessage(message); amfSerializers.Flush(); buffer = new byte[amfSerializers.BaseStream.Length]; stream.Position = 0; stream.Read(buffer, 0, buffer.Length); return(buffer); }
private void BeginRequestFlashCall(IAsyncResult ar) { try { AmfRequestData amfRequestData = ar.AsyncState as AmfRequestData; if (amfRequestData != null) { Stream requestStream = amfRequestData.Request.EndGetRequestStream(ar); AMFSerializer amfSerializer = new AMFSerializer(requestStream); amfSerializer.WriteMessage(amfRequestData.AmfMessage); amfSerializer.Flush(); amfSerializer.Close(); amfRequestData.Request.BeginGetResponse(BeginResponseFlashCall, amfRequestData); } } catch (Exception ex) { _netConnection.RaiseNetStatus(ex); } }
private void BeginRequestFlexCall(IAsyncResult ar) { try { RequestData asyncState = ar.AsyncState as RequestData; if (asyncState != null) { AMFSerializer serializer = new AMFSerializer(asyncState.Request.EndGetRequestStream(ar)); serializer.WriteMessage(asyncState.AmfMessage); serializer.Flush(); serializer.Close(); asyncState.Request.BeginGetResponse(new AsyncCallback(this.BeginResponseFlexCall), asyncState); } } catch (Exception exception) { this._netConnection.RaiseNetStatus(exception); } }
private async void sendBtn_Click(object sender, EventArgs e) { object[] arguments = { Convert.ToInt32(textBox1.Text) }; AMFMessage _amf = new AMFMessage(3); _amf.AddHeader(new AMFHeader("id", false, Hash.createChecksum(arguments))); _amf.AddHeader(new AMFHeader("needClassName", false, true)); _amf.AddBody(new AMFBody("MovieStarPlanet.WebService.UserSession.AMFUserSessionService.GetActorNameFromId", "/1", arguments)); MemoryStream mStream = new MemoryStream(); AMFSerializer serialize = new AMFSerializer(mStream); serialize.WriteMessage(_amf); HttpClient client = new HttpClient(); byte[] AMFBytes = Encoding.Default.GetBytes(Encoding.Default.GetString(mStream.ToArray())); ///Set referer to send AMF without 404 error Uri referer = new Uri("https://assets.mspcdns.com/msp/91.0.2/Main_20200728_110605.swf"); client.DefaultRequestHeaders.Referrer = referer; try { string gateway = "https://ws-" + comboBox1.Text + ".mspapis.com/msp/91.0.6/Gateway.aspx?method=MovieStarPlanet.WebService.UserSession.AMFUserSessionService.GetActorNameFromId"; var AMFHttpClientByteArray = new ByteArrayContent(AMFBytes); AMFHttpClientByteArray.Headers.ContentType = new MediaTypeHeaderValue("application/x-amf"); var response = await client.PostAsync(gateway, AMFHttpClientByteArray); //Response string responseString = response.Content.ReadAsStringAsync().Result; string final = JsonConvert.SerializeObject(responseString); MessageBox.Show(final); } catch (WebException exception) { MessageBox.Show("Error!" + exception); } }
/// <summary> /// 用户认证 /// </summary> /// <returns></returns> private byte[] AuthenticateUser(string userID, string psd, string responseNo) { RemotingMessage rtMsg = new RemotingMessage(); rtMsg.source = null; rtMsg.operation = "authenticateUser"; rtMsg.clientId = Guid.NewGuid().ToString().ToUpper(); rtMsg.messageId = Guid.NewGuid().ToString().ToUpper(); rtMsg.destination = "userRO"; rtMsg.timestamp = 0; rtMsg.timeToLive = 0; rtMsg.headers.Add(RemotingMessage.FlexClientIdHeader, Guid.NewGuid().ToString().ToUpper()); rtMsg.headers.Add(RemotingMessage.EndpointHeader, "my-amf"); List <object> bodys = new List <object>(); bodys.Add(userID); bodys.Add(psd); rtMsg.body = bodys.ToArray(); AMFMessage _amf3 = new AMFMessage(3);// 创建 AMF List <RemotingMessage> lstR = new List <RemotingMessage>(); lstR.Add(rtMsg); AMFBody _amfbody = new AMFBody("null", "/" + responseNo, lstR.ToArray()); _amf3.AddBody(_amfbody); MemoryStream _Memory = new MemoryStream(); //内存流 AMFSerializer _Serializer = new AMFSerializer(_Memory); //序列化 _Serializer.WriteMessage(_amf3); //将消息写入 return(_Memory.ToArray()); }