private static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding) { Stream stream = null; StreamReader reader = null; try { // 以字符流的方式读取HTTP响应 stream = rsp.GetResponseStream(); switch (rsp.ContentEncoding) { case "gzip": stream = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress); break; case "deflate": stream = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Decompress); break; } reader = new StreamReader(stream, encoding); return reader.ReadToEnd(); } finally { // 释放资源 if (reader != null) reader.Close(); if (stream != null) stream.Close(); if (rsp != null) rsp.Close(); } }
public static string Decompress(string strSource, int length) { byte[] buffer = Convert.FromBase64String(strSource); System.IO.MemoryStream ms = new System.IO.MemoryStream(); ms.Write(buffer, 0, buffer.Length); ms.Position = 0; System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Decompress); stream.Flush(); int nSize = length; byte[] decompressBuffer = new byte[nSize]; int nSizeIncept = stream.Read(decompressBuffer, 0, nSize); stream.Close(); return System.Text.Encoding.Unicode.GetString(decompressBuffer, 0, nSizeIncept);//转换为普通的字符串 }
public static byte[] Unzip(byte[] data) { System.IO.Compression.CompressionMode mode = System.IO.Compression.CompressionMode.Decompress; System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream( new System.IO.MemoryStream(data), mode); System.IO.MemoryStream mem = new System.IO.MemoryStream(); byte[] buffer = new byte[4096]; while (true) { int count = stream.Read(buffer, 0, buffer.Length); if (count != 0) mem.Write(buffer, 0, count); if (count != buffer.Length) break; } stream.Close(); return mem.ToArray(); }
public static string Compress(string strSource) { if (strSource == null) throw new System.ArgumentException("字符串为空!"); System.Text.Encoding encoding = System.Text.Encoding.Unicode; byte[] buffer = encoding.GetBytes(strSource); System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress, true); stream.Write(buffer, 0, buffer.Length); stream.Close(); buffer = ms.ToArray(); ms.Close(); //return buffer; return Convert.ToBase64String(buffer); //将压缩后的byte[]转换为Base64String }
public static object DecompressAndDecode(byte[] input) { MemoryStream compressedStream = new MemoryStream(input); compressedStream.Seek(2, SeekOrigin.Begin); //skip zlib header, we're only interested in the deflated bytes byte[] outputBytes = new byte[4096]; DeflateStream stream = new DeflateStream(compressedStream, CompressionMode.Decompress); try { stream.Read(outputBytes, 0, (int) input.Length); stream.Flush(); stream.Close(); return Rencode.Decode(outputBytes); } catch (Exception e) { //Console.WriteLine("Exception reading stream"); } return null; }
public static unsafe byte[] Compress(byte[] buffer) { using (var compressStream = new System.IO.MemoryStream()) using (var compressor = new System.IO.Compression.DeflateStream(compressStream, System.IO.Compression.CompressionLevel.Optimal)) { UInt32 adder = 0; fixed(byte *b = buffer) { adder = CalcAdler32(b, (UInt32)buffer.Length); } compressor.Write(buffer, 0, buffer.Count()); compressor.Close(); var compressed = compressStream.ToArray(); List <byte[]> dst = new List <byte[]>(); dst.Add(new byte[] { 0x78, 0x9c }); dst.Add(compressed); dst.Add(BitConverter.GetBytes(adder).Reverse().ToArray()); return(dst.SelectMany(_ => _).ToArray()); } }
/// <summary> /// 解压数据 /// </summary> /// <param name="data"></param> /// <returns></returns> private byte[] DecompressData(byte[] data) { using (MemoryStream outBuffer = new MemoryStream()) { using (System.IO.Compression.DeflateStream compressedzipStream = new System.IO.Compression.DeflateStream(new MemoryStream(data, 2, data.Length - 2), System.IO.Compression.CompressionMode.Decompress)) { byte[] block = new byte[1024]; while (true) { int bytesRead = compressedzipStream.Read(block, 0, block.Length); if (bytesRead <= 0) { break; } else { outBuffer.Write(block, 0, bytesRead); } } compressedzipStream.Close(); return(outBuffer.ToArray()); } } }
private void WriteDataChunks() { byte[] pixels = _image.Pixels; byte[] data = new byte[_image.PixelWidth * _image.PixelHeight * 4 + _image.PixelHeight]; int rowLength = _image.PixelWidth * 4 + 1; for (int y = 0; y < _image.PixelHeight; y++) { byte compression = 0; if (y > 0) { compression = 2; } data[y * rowLength] = compression; for (int x = 0; x < _image.PixelWidth; x++) { // Calculate the offset for the new array. int dataOffset = y * rowLength + x * 4 + 1; // Calculate the offset for the original pixel array. int pixelOffset = (y * _image.PixelWidth + x) * 4; data[dataOffset + 0] = pixels[pixelOffset + 0]; data[dataOffset + 1] = pixels[pixelOffset + 1]; data[dataOffset + 2] = pixels[pixelOffset + 2]; data[dataOffset + 3] = pixels[pixelOffset + 3]; if (y > 0) { int lastOffset = ((y - 1) * _image.PixelWidth + x) * 4; data[dataOffset + 0] -= pixels[lastOffset + 0]; data[dataOffset + 1] -= pixels[lastOffset + 1]; data[dataOffset + 2] -= pixels[lastOffset + 2]; data[dataOffset + 3] -= pixels[lastOffset + 3]; } } } byte[] buffer = null; int bufferLength = 0; MemoryStream memoryStream = null; try { memoryStream = new MemoryStream(); //using (Ionic.Zlib.DeflateStream zStream = new Ionic.Zlib.DeflateStream(memoryStream, Ionic.Zlib.CompressionMode.Compress)) using (System.IO.Compression.DeflateStream zStream = new System.IO.Compression.DeflateStream(memoryStream, System.IO.Compression.CompressionMode.Compress)) { zStream.Write(data, 0, data.Length); zStream.Flush(); bufferLength = (int)memoryStream.Length; buffer = memoryStream.GetBuffer(); zStream.Close(); } //using (DeflaterOutputStream zStream = new DeflaterOutputStream(memoryStream)) //{ // zStream.Write(data, 0, data.Length); // zStream.Flush(); // zStream.Finish(); // bufferLength = (int)memoryStream.Length; // buffer = memoryStream.GetBuffer(); //} } finally { if (memoryStream != null) { memoryStream.Dispose(); } } int numChunks = bufferLength / MaxBlockSize; if (bufferLength % MaxBlockSize != 0) { numChunks++; } for (int i = 0; i < numChunks; i++) { int length = bufferLength - i * MaxBlockSize; if (length > MaxBlockSize) { length = MaxBlockSize; } WriteChunk(PngChunkTypes.Data, buffer, i * MaxBlockSize, length); } }
public unsafe void CreateTexture(BinaryReader reader, int[] palette) { if (Width == 0 || Height == 0) return; Image = new Bitmap(Width, Height); MaskImage = new Bitmap(1, 1); BitmapData data = Image.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); byte[] bytes = new byte[0]; byte[] maskbytes = new byte[0]; MemoryStream output; switch (nType) { case 0://wemade wil file uncompressed if (palette.Length > 256) { bo16bit = true; nSize = nSize * 2; } bytes = reader.ReadBytes(nSize); break; case 1://shanda wzl file compressed case 4://shanda miz file compressed output = new MemoryStream(); Ionic.Zlib.ZlibStream deflateStream = new Ionic.Zlib.ZlibStream(output,Ionic.Zlib.CompressionMode.Decompress); deflateStream.Write(reader.ReadBytes(nSize), 0, nSize); bytes = output.ToArray(); deflateStream.Close(); output.Close(); break; case 2: byte Compressed = reader.ReadByte(); reader.ReadBytes(5); if (Compressed != 8) { bytes = reader.ReadBytes(nSize - 6); break; } MemoryStream input = new MemoryStream(reader.ReadBytes(nSize-6)); output = new MemoryStream(); byte[] buffer = new byte[10]; System.IO.Compression.DeflateStream decompress = new System.IO.Compression.DeflateStream(input, System.IO.Compression.CompressionMode.Decompress); int len; while ((len = decompress.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, len); } bytes = output.ToArray(); decompress.Close(); output.Close(); input.Close(); break; case 3: MaskImage = new Bitmap(Width, Height); byte[][] DecodedPixels = DecompressWemadeMir3(reader,Width,Height,nSize); if (DecodedPixels != null) { bytes = DecodedPixels[0]; if (HasMask) maskbytes = DecodedPixels[1]; } else { HasMask = false; bytes = new byte[Width * Height * 2]; } break; } int index = 0; int* scan0 = (int*) data.Scan0; { for (int y = Height - 1; y >= 0; y--) { for (int x = 0; x < Width; x++) { if (bo16bit) scan0[y * Width + x] = convert16bitTo32bit(bytes[index++] + (bytes[index++] << 8)); else scan0[y*Width + x] = palette[bytes[index++]]; } if (((nType == 1) || (nType == 4)) & (Width % 4 > 0)) index += WidthBytes(bo16bit ? 16 : 8, Width) - (Width * (bo16bit ? 2 : 1)); } } Image.UnlockBits(data); index = 0; if (HasMask) { BitmapData Maskdata = MaskImage.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); int* maskscan0 = (int*)Maskdata.Scan0; { for (int y = Height - 1; y >= 0; y--) { for (int x = 0; x < Width; x++) maskscan0[y * Width + x] = convert16bitTo32bit(maskbytes[index++] + (maskbytes[index++] << 8)); } } MaskImage.UnlockBits(Maskdata); } }
public void Serialize(Stream fs) { bPayloadAtEndOfFile = ((BulkDataFlags & 0x01) == 0x01); bCompressed = ((BulkDataFlags & 0x02) == 0x02); if (bCompressed) { MemoryStream ms = new MemoryStream(); WriteInt64(ms, PackageFileTag); WriteInt64(ms, CompressionChunkSize); Int64 CompressedSizeOffset = ms.Position; WriteInt64(ms, 0); WriteInt64(ms, BulkDataDecompressed.Length); TotalChunkCount = (BulkDataDecompressed.Length + CompressionChunkSize - 1) / CompressionChunkSize; List <Int64> ChanksOffsetInfo = new List <Int64>(); for (int j = 0; j < TotalChunkCount; j++) { ChanksOffsetInfo.Add(ms.Position); WriteInt64(ms, 0); WriteInt64(ms, 0); } int nCurrentOffset = 0; int i = 0; Int64 nTotalSize = 0; while (nCurrentOffset < BulkDataDecompressed.Length) { ms.Seek(0, SeekOrigin.End); Int64 CurrentCompressionChunkSize = CompressionChunkSize; if (BulkDataDecompressed.Length - nCurrentOffset < CurrentCompressionChunkSize) { CurrentCompressionChunkSize = BulkDataDecompressed.Length - nCurrentOffset; } MemoryStream ms_src = new MemoryStream(BulkDataDecompressed, nCurrentOffset, (int)CurrentCompressionChunkSize); nCurrentOffset += (int)CurrentCompressionChunkSize; Int64 nCurFsOffset = ms.Position; WriteUInt16(ms, 0x9C78); System.IO.Compression.DeflateStream ms_compressed = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionLevel.Optimal, true); ms_src.CopyTo(ms_compressed); ms_compressed.Close(); Adler32Computer ad32 = new Adler32Computer(); byte[] BufForAdlerCalc = new byte[ms_src.Length]; ms_src.Seek(0, SeekOrigin.Begin); ms_src.Read(BufForAdlerCalc, 0, BufForAdlerCalc.Length); ad32.Update(BufForAdlerCalc, 0, BufForAdlerCalc.Length); byte[] AdlerRes = BitConverter.GetBytes(ad32.Checksum); WriteByte(ms, AdlerRes[3]); WriteByte(ms, AdlerRes[2]); WriteByte(ms, AdlerRes[1]); WriteByte(ms, AdlerRes[0]); Int64 nNewFsOffset = ms.Position; ms.Seek(ChanksOffsetInfo[i], SeekOrigin.Begin); WriteInt64(ms, nNewFsOffset - nCurFsOffset); nTotalSize += nNewFsOffset - nCurFsOffset; WriteInt64(ms, CurrentCompressionChunkSize); i++; } ms.Seek(CompressedSizeOffset, SeekOrigin.Begin); WriteInt64(ms, nTotalSize); BulkData = new byte[ms.Length]; ms.Seek(0, SeekOrigin.Begin); ms.Read(BulkData, 0, BulkData.Length); } WriteUInt32(fs, BulkDataFlags); WriteInt32(fs, BulkDataDecompressed.Length); WriteInt32(fs, BulkData.Length); if (!bPayloadAtEndOfFile) { WriteInt64(fs, fs.Position + 8); fs.Write(BulkData, 0, BulkData.Length); } else { Int64 nTotalLength = 0; for (int i = 0; i < BulkStorage.Count; i++) { nTotalLength += BulkStorage[i].LongLength; } WriteInt64(fs, nTotalLength); BulkStorage.Add(BulkData); } }
public void CreateFromStream(Stream _stream, DateTime _cacheTime, EventHandler <CacheWriteProgressChangedEventArgs> progressCallback) { Microsoft.VisualBasic.FileIO.FileSystem.CreateDirectory(this.innerfi.DirectoryName); bool cancel = false; using (BufferedStream bufferStream = new BufferedStream(_stream, 1024)) using (FileStream fs = this.innerfi.Create()) { byte[] laiwhg; if (this.IsCompressedStream(bufferStream, out laiwhg)) { BinaryWriter bw = new BinaryWriter(fs); bw.Write(false); bw.Flush(); long totalread = 0; if (laiwhg != null && laiwhg.Length > 0) { fs.Write(laiwhg, 0, laiwhg.Length); totalread = laiwhg.Length; } byte[] arr = new byte[1024]; int readbyte = bufferStream.Read(arr, 0, arr.Length); while (readbyte > 0) { if (cancel) { fs.Flush(); fs.Close(); this.innerfi.Delete(); return; } fs.Write(arr, 0, readbyte); totalread += readbyte; if (progressCallback != null) { var myEvent = new CacheWriteProgressChangedEventArgs(totalread); progressCallback.Invoke(this, myEvent); cancel = myEvent.Cancel; } readbyte = bufferStream.Read(arr, 0, arr.Length); } fs.Flush(); } else { BinaryWriter bw = new BinaryWriter(fs); bw.Write(true); bw.Flush(); using (System.IO.Compression.DeflateStream localfile = new System.IO.Compression.DeflateStream(fs, System.IO.Compression.CompressionMode.Compress)) { long totalread = 0; if (laiwhg != null && laiwhg.Length > 0) { localfile.Write(laiwhg, 0, laiwhg.Length); totalread = laiwhg.Length; } byte[] arr = new byte[1024]; int readbyte = bufferStream.Read(arr, 0, arr.Length); while (readbyte > 0) { if (cancel) { localfile.Flush(); localfile.Close(); this.innerfi.Delete(); return; } localfile.Write(arr, 0, readbyte); totalread += readbyte; if (progressCallback != null) { var myEvent = new CacheWriteProgressChangedEventArgs(totalread); progressCallback.Invoke(this, myEvent); cancel = myEvent.Cancel; } readbyte = bufferStream.Read(arr, 0, arr.Length); } localfile.Flush(); } } } this.innerfi.CreationTimeUtc = _cacheTime; this.innerfi.LastWriteTimeUtc = _cacheTime; if (!this._disposed) { this.CacheCreateCompleted?.Invoke(this, System.EventArgs.Empty); } }
public unsafe void CreateTexture(BinaryReader reader, int[] palette) { try { if (Width == 0 || Height == 0) { return; } Image = new Bitmap(Width, Height); MaskImage = new Bitmap(1, 1); BitmapData data = Image.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); byte[] bytes = new byte[0]; byte[] maskbytes = new byte[0]; MemoryStream output; switch (nType) { case 0: //wemade wil file uncompressed if (palette.Length > 256) { bo16bit = true; nSize = nSize * 2; } bytes = reader.ReadBytes(nSize); break; case 1: //shanda wzl file compressed case 4: //shanda miz file compressed output = new MemoryStream(); Ionic.Zlib.ZlibStream deflateStream = new Ionic.Zlib.ZlibStream(output, Ionic.Zlib.CompressionMode.Decompress); deflateStream.Write(reader.ReadBytes(nSize), 0, nSize); bytes = output.ToArray(); deflateStream.Close(); output.Close(); break; case 2: byte Compressed = reader.ReadByte(); reader.ReadBytes(5); if (Compressed != 8) { bytes = reader.ReadBytes(nSize - 6); break; } MemoryStream input = new MemoryStream(reader.ReadBytes(nSize - 6)); output = new MemoryStream(); byte[] buffer = new byte[10]; System.IO.Compression.DeflateStream decompress = new System.IO.Compression.DeflateStream(input, System.IO.Compression.CompressionMode.Decompress); int len; while ((len = decompress.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, len); } bytes = output.ToArray(); decompress.Close(); output.Close(); input.Close(); break; case 3: MaskImage = new Bitmap(Width, Height); byte[][] DecodedPixels = DecompressWemadeMir3(reader, Width, Height, nSize); if (DecodedPixels != null) { bytes = DecodedPixels[0]; if (HasMask) { maskbytes = DecodedPixels[1]; } } else { HasMask = false; bytes = new byte[Width * Height * 2]; } break; } int index = 0; int *scan0 = (int *)data.Scan0; { for (int y = Height - 1; y >= 0; y--) { for (int x = 0; x < Width; x++) { if (bo16bit) { scan0[y * Width + x] = convert16bitTo32bit(bytes[index++] + (bytes[index++] << 8)); } else { scan0[y * Width + x] = palette[bytes[index++]]; } } if (((nType == 1) || (nType == 4)) & (Width % 4 > 0)) { index += WidthBytes(bo16bit ? 16 : 8, Width) - (Width * (bo16bit ? 2 : 1)); } } } Image.UnlockBits(data); index = 0; if (HasMask) { BitmapData Maskdata = MaskImage.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); int * maskscan0 = (int *)Maskdata.Scan0; { for (int y = Height - 1; y >= 0; y--) { for (int x = 0; x < Width; x++) { maskscan0[y * Width + x] = convert16bitTo32bit(maskbytes[index++] + (maskbytes[index++] << 8)); } } } MaskImage.UnlockBits(Maskdata); } } catch (Exception) { } }
private async void Listen() { Stream _netStream = _clientSocket.InputStream.AsStreamForRead(1024); byte[] stableBuffer = new byte[1024]; while (true) { if (!_StartState) { return; } try { _netStream.ReadB(stableBuffer, 0, 4); var packetlength = BitConverter.ToInt32(stableBuffer, 0); packetlength = IPAddress.NetworkToHostOrder(packetlength); if (packetlength < 16) { throw new NotSupportedException("协议失败: (L:" + packetlength + ")"); } _netStream.ReadB(stableBuffer, 0, 2); //magic _netStream.ReadB(stableBuffer, 0, 2); //protocol_version _netStream.ReadB(stableBuffer, 0, 4); var typeId = BitConverter.ToInt32(stableBuffer, 0); typeId = IPAddress.NetworkToHostOrder(typeId); _netStream.ReadB(stableBuffer, 0, 4);//magic, params? var playloadlength = packetlength - 16; if (playloadlength == 0) { continue;//没有内容了 } typeId = typeId - 1; var buffer = new byte[playloadlength]; _netStream.ReadB(buffer, 0, playloadlength); if (typeId == 2) { var viewer = BitConverter.ToUInt32(buffer.Take(4).Reverse().ToArray(), 0); //观众人数 if (NewMessage != null) { NewMessage(null, new LiveDanmuModel() { type = LiveDanmuTypes.Viewer, viewer = Convert.ToInt32(viewer) }); } Debug.WriteLine(viewer); continue; } var json_str = ""; try { //临时解决方案,可以优化 //参考https://github.com/Bililive/BililiveRecorder using (MemoryStream outBuffer = new MemoryStream()) { using (System.IO.Compression.DeflateStream compressedzipStream = new System.IO.Compression.DeflateStream(new MemoryStream(buffer, 2, playloadlength - 2), System.IO.Compression.CompressionMode.Decompress)) { byte[] block = new byte[1024]; while (true) { int bytesRead = compressedzipStream.Read(block, 0, block.Length); if (bytesRead <= 0) { break; } else { outBuffer.Write(block, 0, bytesRead); } } compressedzipStream.Close(); buffer = outBuffer.ToArray(); } } json_str = Regex.Replace(Encoding.UTF8.GetString(buffer, 16, buffer.Length - 16), "}\\0\\0.*?\\0\\0{", "},{"); } catch (Exception) { json_str = Encoding.UTF8.GetString(buffer, 0, buffer.Length); } if (json_str.Trim().Length != 0) { json_str = "[" + json_str + "]"; Debug.WriteLine(json_str); JArray json_array = JArray.Parse(json_str); foreach (var obj in json_array) { if (obj["cmd"] == null) { continue; } if (obj["cmd"].ToString().Contains("DANMU_MSG")) { var v = new DanmuMsgModel(); if (obj["info"] != null && obj["info"].ToArray().Length != 0) { v.text = obj["info"][1].ToString(); if (obj["info"][2] != null && obj["info"][2].ToArray().Length != 0) { v.username = obj["info"][2][1].ToString() + ":"; //v.usernameColor = GetColor(obj["info"][2][0].ToString()); if (obj["info"][2][3] != null && Convert.ToInt32(obj["info"][2][3].ToString()) == 1) { v.vip = "老爷"; v.isVip = Visibility.Visible; } if (obj["info"][2][4] != null && Convert.ToInt32(obj["info"][2][4].ToString()) == 1) { v.vip = "年费老爷"; v.isVip = Visibility.Collapsed; v.isBigVip = Visibility.Visible; } if (obj["info"][2][2] != null && Convert.ToInt32(obj["info"][2][2].ToString()) == 1) { v.vip = "房管"; v.isAdmin = Visibility.Visible; } } if (obj["info"][3] != null && obj["info"][3].ToArray().Length != 0) { v.medal_name = obj["info"][3][1].ToString(); v.medal_lv = obj["info"][3][0].ToString(); v.medalColor = obj["info"][3][4].ToString(); v.hasMedal = Visibility.Visible; } if (obj["info"][4] != null && obj["info"][4].ToArray().Length != 0) { v.ul = "UL" + obj["info"][4][0].ToString(); v.ulColor = obj["info"][4][2].ToString(); } if (obj["info"][5] != null && obj["info"][5].ToArray().Length != 0) { v.user_title = obj["info"][5][0].ToString(); v.hasTitle = Visibility.Visible; } if (NewMessage != null) { NewMessage(null, new LiveDanmuModel() { type = LiveDanmuTypes.Danmu, value = v }); } } } //19/10/01,cmd DANMU_MSG变成了DANMU_MSG:4:0:2:2:2:0 switch (obj["cmd"].ToString()) { //case "DANMU_MSG": // break; case "SEND_GIFT": var g = new GiftMsgModel(); if (obj["data"] != null) { g.uname = obj["data"]["uname"].ToString(); g.action = obj["data"]["action"].ToString(); g.giftId = Convert.ToInt32(obj["data"]["giftId"].ToString()); g.giftName = obj["data"]["giftName"].ToString(); g.num = obj["data"]["num"].ToString(); g.uid = obj["data"]["uid"].ToString(); if (NewMessage != null) { NewMessage(null, new LiveDanmuModel() { type = LiveDanmuTypes.Gift, value = g }); } } break; case "WELCOME": var w = new WelcomeMsgModel(); if (obj["data"] != null) { w.uname = obj["data"]["uname"].ToString(); w.uid = obj["data"]["uid"].ToString(); w.svip = obj["data"]["vip"].ToInt32() != 1; if (NewMessage != null) { NewMessage(null, new LiveDanmuModel() { type = LiveDanmuTypes.Welcome, value = w }); } } break; case "SYS_MSG": if (obj["msg"] != null) { if (NewMessage != null) { NewMessage(null, new LiveDanmuModel() { type = LiveDanmuTypes.SystemMsg, value = obj["msg"].ToString() }); } } break; case "ANCHOR_LOT_START": if (obj["data"] != null) { if (NewMessage != null) { NewMessage(null, new LiveDanmuModel() { type = LiveDanmuTypes.ANCHOR_LOT_START, value = obj["data"].ToString() }); } } break; case "ANCHOR_LOT_AWARD": if (obj["data"] != null) { if (NewMessage != null) { NewMessage(null, new LiveDanmuModel() { type = LiveDanmuTypes.ANCHOR_LOT_AWARD, value = obj["data"].ToString() }); } } break; default: break; } await Task.Delay(delay); } } // } } catch (Exception ex) { LogHelper.Log("加载直播弹幕失败", LogType.ERROR, ex); } await Task.Delay(delay); } }
void showPPXHome() { SetContentView(Resource.Layout.PrepexHome); var closeButton = FindViewById <Button>(Resource.Id.buttonClose); closeButton.Click += (sender, e) => { //close activity StartActivity(typeof(LauncherActivity)); }; var buttonClientEvaluation = FindViewById <Button>(Resource.Id.buttonClientEvaluation); buttonClientEvaluation.Click += (sender, e) => { StartActivity(typeof(IlaspMainStart)); }; buttonClientEvaluation.Text = "Add Survey"; var buttonUnscheduled = FindViewById <Button>(Resource.Id.buttonUnscheduled); buttonUnscheduled.Visibility = Android.Views.ViewStates.Gone; var buttonDeviceRemovalVisit = FindViewById <Button>(Resource.Id.buttonDeviceRemovalVisit); buttonDeviceRemovalVisit.Visibility = Android.Views.ViewStates.Gone; //buttonDeviceRemovalVisit.Click += (sender, e) => //{ // StartActivity(typeof(VmmcClientSelectionActivity), typeof(VmmcPostOp1)); //}; //buttonDeviceRemovalVisit.Text = "Post Operation"; var buttonPostRemovalVisit = FindViewById <Button>(Resource.Id.buttonPostRemovalVisit); buttonPostRemovalVisit.Visibility = Android.Views.ViewStates.Gone; //buttonViewList var buttonViewList = FindViewById <Button>(Resource.Id.buttonViewList); buttonViewList.Click += (sender, e) => { //StartActivity(typeof(lspFilteredGridDisplayActivity)); //InitializeLocationManager(); }; buttonViewList.Text = "Get GPS"; buttonViewList.Visibility = Android.Views.ViewStates.Invisible; //buttonEditRecords var buttonEditRecords = FindViewById <Button>(Resource.Id.buttonEditRecords); buttonEditRecords.Click += (sender, e) => { StartActivity(typeof(lspClientSelectionActivity), typeof(lspRecordSelectorActivity)); }; var buttonSupplies = FindViewById <Button>(Resource.Id.buttonSupplies); buttonSupplies.Visibility = Android.Views.ViewStates.Gone; //var unsyncdRecs = new CloudDb(Assets).GetRecordsToSync(); var buttonViewRecordSummaries = FindViewById <Button>(Resource.Id.buttonViewRecordSummaries); buttonViewRecordSummaries.Click += (sender, e) => { //await getClientSummaryReport(new lspProvider(), Constants.LSP_KIND_DISPLAYNAMES); var unsyncdRecs = new store.CloudDb(Assets).GetRecordsToSync(); var js = Newtonsoft.Json.JsonConvert.SerializeObject(unsyncdRecs); var bytes = System.Text.Encoding.UTF8.GetBytes(js); var b64 = string.Empty; using (var input = new System.IO.MemoryStream(bytes)) { using (var outStream = new System.IO.MemoryStream()) using (var deflateStream = new System.IO.Compression .DeflateStream(outStream, System.IO.Compression.CompressionMode.Compress)) { input.CopyTo(deflateStream); deflateStream.Close(); b64 = System.Convert.ToBase64String(outStream.ToArray()); } } setTextResults(b64); }; buttonViewRecordSummaries.Text = "Get unsynced clients"; buttonViewRecordSummaries.Visibility = Android.Views.ViewStates.Invisible; }
public async Task CompressionTest(BucketCompressionAlgorithm alg) { bool overshoot = false; var baseStream = new MemoryStream(); for (int i = 0; i < 10; i++) { baseStream.Write(Guid.NewGuid().ToByteArray(), 0, 16); } for (int i = 0; i < 10; i++) { baseStream.Write(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }, 0, 8); } var baseData = baseStream.ToArray(); Bucket compressed; switch (alg) { case BucketCompressionAlgorithm.ZLib: #if !NET6_0_OR_GREATER compressed = baseData.AsBucket().Compress(alg); #else { var ms = new MemoryStream(); var zs = new System.IO.Compression.ZLibStream(ms, System.IO.Compression.CompressionLevel.Optimal); zs.Write(baseData, 0, baseData.Length); zs.Close(); compressed = ms.ToArray().AsBucket(); } #endif break; case BucketCompressionAlgorithm.GZip: { var ms = new MemoryStream(); var zs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionLevel.Optimal); zs.Write(baseData, 0, baseData.Length); zs.Close(); compressed = ms.ToArray().AsBucket(); break; } case BucketCompressionAlgorithm.Deflate: { var ms = new MemoryStream(); var zs = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionLevel.Optimal); zs.Write(baseData, 0, baseData.Length); zs.Close(); compressed = ms.ToArray().AsBucket(); break; } #if NET6_0_OR_GREATER case BucketCompressionAlgorithm.Brotli: { var ms = new MemoryStream(); var zs = new System.IO.Compression.BrotliStream(ms, System.IO.Compression.CompressionLevel.Optimal); zs.Write(baseData, 0, baseData.Length); zs.Close(); compressed = ms.ToArray().AsBucket(); overshoot = true; break; } #endif default: throw new InvalidOperationException(); } var finishData = overshoot ? Array.Empty <byte>() : Guid.NewGuid().ToByteArray(); var compressedData = await compressed.Append(finishData.AsBucket()).ToArrayAsync(); ushort firstTwo = NetBitConverter.ToUInt16(compressedData, 0); switch (alg) { case BucketCompressionAlgorithm.GZip: Assert.AreEqual(0x1F8B, firstTwo, $"Got 0x{firstTwo:x4}"); break; case BucketCompressionAlgorithm.ZLib: bool isZlib = new ushort[] { 0x7801, 0x789C, 0x78da }.Contains(firstTwo); Assert.IsTrue(isZlib, $"Got 0x{firstTwo:x4}"); break; case BucketCompressionAlgorithm.Deflate: // FirstTwo can be anything break; } var inner = compressedData.AsBucket(); var bb = await inner.Decompress(alg).ReadFullAsync(4096); Assert.AreEqual(baseData.Length, bb.Length); var decompressed = bb.ToArray(); Assert.IsTrue(decompressed.SequenceEqual(baseData), "Same data after decompression"); bb = await inner.ReadFullAsync(4096); Assert.AreEqual(finishData.Length, bb.Length); Assert.IsTrue(bb.ToArray().SequenceEqual(finishData)); var r = await baseData.AsBucket().Compress(alg).ToArrayAsync(); Stream rs; switch (alg) { case BucketCompressionAlgorithm.ZLib: rs = r.AsBucket().Decompress(BucketCompressionAlgorithm.ZLib).AsStream(); break; case BucketCompressionAlgorithm.GZip: rs = new System.IO.Compression.GZipStream(new MemoryStream(r), System.IO.Compression.CompressionMode.Decompress); break; case BucketCompressionAlgorithm.Deflate: rs = new System.IO.Compression.DeflateStream(new MemoryStream(r), System.IO.Compression.CompressionMode.Decompress); break; #if NET6_0_OR_GREATER case BucketCompressionAlgorithm.Brotli: rs = new System.IO.Compression.BrotliStream(new MemoryStream(r), System.IO.Compression.CompressionMode.Decompress); break; #endif default: throw new InvalidOperationException(); } byte[] resultBytes = new byte[4096]; Assert.AreEqual(baseData.Length, rs.Read(resultBytes, 0, resultBytes.Length)); }
public static byte[] Zip(byte[] data) { System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.IO.Compression.DeflateStream zStream = new System.IO.Compression.DeflateStream( stream, System.IO.Compression.CompressionMode.Compress, true); zStream.Write(data, 0, data.Length); zStream.Close(); return stream.ToArray(); }
/// <summary> /// Closes the fileStream and removes the FileStreamAssembler from the parentAssemblerList /// </summary> internal void FinishAssembling() { this.isActive = false; try { foreach (byte[] data in tcpPacketBufferWindow.Values) { this.fileStream.Write(data, 0, data.Length); } this.fileStream.Flush(); } catch (Exception ex) { if (fileStream != null) { parentAssemblerList.PacketHandler.OnAnomalyDetected("Error writing final data to file \"" + fileStream.Name + "\".\n" + ex.Message); } else { parentAssemblerList.PacketHandler.OnAnomalyDetected("Error writing final data to file \"" + this.filename + "\".\n" + ex.Message); } } tcpPacketBufferWindow.Clear(); parentAssemblerList.Remove(this, false); string destinationPath = GetFilePath(false); //I need to create the directory here since the file might either be moved to this located or a new file will be created there from a stream string directoryName = destinationPath.Substring(0, destinationPath.Length - this.filename.Length); if (this.fileStreamType != FileStreamTypes.HttpPostMimeMultipartFormData && !System.IO.Directory.Exists(directoryName)) { try { System.IO.Directory.CreateDirectory(directoryName); } catch (Exception e) { parentAssemblerList.PacketHandler.OnAnomalyDetected("Error creating directory \"" + directoryName + "\".\n" + e.Message); //parentAssemblerList.PacketHandler.ParentForm.ShowError("Error creating directory \""+directoryName+"\".\n"+e.Message); } } if (System.IO.File.Exists(destinationPath)) { try { System.IO.File.Delete(destinationPath); } catch (Exception e) { parentAssemblerList.PacketHandler.OnAnomalyDetected("Error deleting file \"" + destinationPath + "\" (tried to replace it)"); //parentAssemblerList.PacketHandler.ParentForm.ShowError("Error deleting file \""+destinationPath+"\" (tried to replace it)"); } } //do some special fixes such as un-chunk data or decompress compressed data if (this.fileStreamType == FileStreamTypes.HttpGetChunked || (parentAssemblerList.DecompressGzipStreams && this.contentEncoding == Packets.HttpPacket.ContentEncodings.Gzip) || this.contentEncoding == Packets.HttpPacket.ContentEncodings.Deflate) { this.fileStream.Position = 0;//move to fileStream start since it needs to be read if (this.fileStreamType == FileStreamTypes.HttpGetChunked && (parentAssemblerList.DecompressGzipStreams && this.contentEncoding == Packets.HttpPacket.ContentEncodings.Gzip)) { using (DeChunkedDataStream deChunkedStream = new DeChunkedDataStream(this.fileStream)) { using (System.IO.Compression.GZipStream decompressedStream = new System.IO.Compression.GZipStream(deChunkedStream, System.IO.Compression.CompressionMode.Decompress)) { try { this.WriteStreamToFile(decompressedStream, destinationPath); } catch (Exception e) { this.parentAssemblerList.PacketHandler.OnAnomalyDetected("Error: Cannot write to file " + destinationPath + " (" + e.Message + ")"); //this.parentAssemblerList.PacketHandler.ParentForm.ShowError("Error: Cannot write to file "+destinationPath+" ("+e.Message+")"); } decompressedStream.Close(); } deChunkedStream.Close(); } } else if (this.fileStreamType == FileStreamTypes.HttpGetChunked && this.contentEncoding == Packets.HttpPacket.ContentEncodings.Deflate) { using (DeChunkedDataStream deChunkedStream = new DeChunkedDataStream(this.fileStream)) { using (System.IO.Compression.DeflateStream decompressedStream = new System.IO.Compression.DeflateStream(deChunkedStream, System.IO.Compression.CompressionMode.Decompress)) { try { this.WriteStreamToFile(decompressedStream, destinationPath); } catch (Exception e) { this.parentAssemblerList.PacketHandler.OnAnomalyDetected("Error: Cannot write to file " + destinationPath + " (" + e.Message + ")"); //this.parentAssemblerList.PacketHandler.ParentForm.ShowError("Error: Cannot write to file "+destinationPath+" ("+e.Message+")"); } decompressedStream.Close(); } deChunkedStream.Close(); } } else if (this.fileStreamType == FileStreamTypes.HttpGetChunked) { using (DeChunkedDataStream deChunkedStream = new DeChunkedDataStream(this.fileStream)) { try { this.WriteStreamToFile(deChunkedStream, destinationPath); } catch (Exception e) { this.parentAssemblerList.PacketHandler.OnAnomalyDetected("Error: Cannot write to file " + destinationPath + " (" + e.Message + ")"); //this.parentAssemblerList.PacketHandler.ParentForm.ShowError("Error: Cannot write to file "+destinationPath+" ("+e.Message+")"); } deChunkedStream.Close(); } } else { using (System.IO.Compression.GZipStream decompressedStream = new System.IO.Compression.GZipStream(this.fileStream, System.IO.Compression.CompressionMode.Decompress)) { try { this.WriteStreamToFile(decompressedStream, destinationPath); } catch (Exception e) { this.parentAssemblerList.PacketHandler.OnAnomalyDetected("Error: Cannot write to file " + destinationPath + " (" + e.Message + ")"); //this.parentAssemblerList.PacketHandler.ParentForm.ShowError("Error: Cannot write to file "+destinationPath+" ("+e.Message+")"); } decompressedStream.Close(); } } this.fileStream.Close(); System.IO.File.Delete(GetFilePath(true));//delete the temp file } else if (this.fileStreamType == FileStreamTypes.HttpPostMimeMultipartFormData) { Mime.UnbufferedReader mimeReader = new PacketParser.Mime.UnbufferedReader(this.fileStream); List <Mime.MultipartPart> parts = new List <PacketParser.Mime.MultipartPart>(); foreach (Mime.MultipartPart part in Mime.PartBuilder.GetParts(mimeReader, this.Details)) { parts.Add(part); } this.parentAssemblerList.PacketHandler.ExtractMultipartFormData(parts, sourceHost, destinationHost, timestamp, this.initialFrameNumber, "TCP " + sourcePort, "TCP " + destinationPort, ApplicationLayerProtocol.Unknown); foreach (Mime.MultipartPart part in parts) { if (part.Attributes["filename"] != null && part.Attributes["filename"].Length > 0 && part.Data != null && part.Data.Length > 0) { //we have a file! string mimeFileLocation = part.Attributes["filename"]; if (mimeFileLocation.Contains("/")) { mimeFileLocation = mimeFileLocation.Substring(0, mimeFileLocation.LastIndexOf('/')); } if (mimeFileLocation.Contains("\\")) { mimeFileLocation = mimeFileLocation.Substring(0, mimeFileLocation.LastIndexOf('\\')); } string mimeFileName = part.Attributes["filename"]; if (mimeFileName.Contains("/") && mimeFileName.Length > mimeFileName.LastIndexOf('/') + 1) { mimeFileName = mimeFileName.Substring(mimeFileName.LastIndexOf('/') + 1); } if (mimeFileName.Contains("\\") && mimeFileName.Length > mimeFileName.LastIndexOf('\\') + 1) { mimeFileName = mimeFileName.Substring(mimeFileName.LastIndexOf('\\') + 1); } using (FileStreamAssembler partAssembler = new FileStreamAssembler(this.parentAssemblerList, this.sourceHost, this.sourcePort, this.destinationHost, this.destinationPort, this.tcpTransfer, FileStreamTypes.HttpPostMimeFileData, mimeFileName, mimeFileLocation, part.Attributes["filename"], this.initialFrameNumber, this.timestamp)) { this.parentAssemblerList.Add(partAssembler); partAssembler.FileContentLength = part.Data.Length; partAssembler.FileSegmentRemainingBytes = part.Data.Length; if (partAssembler.TryActivate()) { partAssembler.AddData(part.Data, 0); } } /* * FixFilenameAndLocation(ref mimeFileName, ref mimeFileLocation); * string mimeFilePath=GetFilePath(false, this.tcpTransfer, this.sourceHost.IPAddress, this.destinationHost.IPAddress, this.sourcePort, this.destinationPort, this.fileStreamType, mimeFileLocation, mimeFileName, this.parentAssemblerList); * Mime.ByteArrayStream partDataStream=new PacketParser.Mime.ByteArrayStream(part.Data, 0); * pare * this.WriteStreamToFile(partDataStream, mimeFilePath); * try { * ReconstructedFile completedFile=new ReconstructedFile(mimeFilePath, sourceHost, destinationHost, sourcePort, destinationPort, tcpTransfer, fileStreamType, "boundary="+details, this.initialFrameNumber, this.timestamp); * parentAssemblerList.PacketHandler.AddReconstructedFile(completedFile); * //parentAssemblerList.PacketHandler.ParentForm.ShowReconstructedFile(completedFile); * } * catch(Exception e) { * this.parentAssemblerList.PacketHandler.OnAnomalyDetected("Error creating reconstructed file: "+e.Message); * }*/ } } this.fileStream.Close(); System.IO.File.Delete(GetFilePath(true)); } else //files which are already completed can simply be moved to their final destination { if (this.fileStream != null) { this.fileStream.Close(); } try { string tmpPath = GetFilePath(true); if (System.IO.File.Exists(tmpPath)) { System.IO.File.Move(tmpPath, destinationPath); } } catch (Exception e) { this.parentAssemblerList.PacketHandler.OnAnomalyDetected("Error moving file \"" + GetFilePath(true) + "\" to \"" + destinationPath + "\". " + e.Message); } } if (System.IO.File.Exists(destinationPath)) { try { ReconstructedFile completedFile = new ReconstructedFile(destinationPath, sourceHost, destinationHost, sourcePort, destinationPort, tcpTransfer, fileStreamType, details, this.initialFrameNumber, this.timestamp); parentAssemblerList.PacketHandler.AddReconstructedFile(completedFile); //parentAssemblerList.PacketHandler.ParentForm.ShowReconstructedFile(completedFile); } catch (Exception e) { this.parentAssemblerList.PacketHandler.OnAnomalyDetected("Error creating reconstructed file: " + e.Message); } } }
void saveIndexedPNG(Stream fs, Form1.frame sprite) { MemoryStream ms = new MemoryStream(); BinaryWriter w = new BinaryWriter(ms); w.Write(0x474E5089); w.Write(0x0A1A0A0D); // IHDR w.Write(toBE(13)); long pos = ms.Position; w.Write(0x52444849); w.Write(toBE(sprite.W)); w.Write(toBE(sprite.H)); w.Write((byte)8); w.Write((byte)3); w.Write((byte)0); w.Write((byte)0); w.Write((byte)0); w.Write(toBE(CRC(ms, pos, ms.Position))); // PLTE w.Write(toBE(3 * 256)); pos = ms.Position; w.Write(0x45544C50); w.Write((byte)0xff); w.Write((byte)0); w.Write((byte)0xff); for (int i = 1; i < pal.Length; i++) { w.Write((byte)(pal[i] >> 16)); w.Write((byte)(pal[i] >> 8)); w.Write((byte)(pal[i])); } w.Write(toBE(CRC(ms, pos, ms.Position))); // tRNS w.Write(toBE(1)); pos = ms.Position; w.Write(0x534E5274); w.Write((byte)0); w.Write(toBE(CRC(ms, pos, ms.Position))); MemoryStream pixeldata = new MemoryStream(); for (int y = 0; y < sprite.H; y++) { pixeldata.WriteByte(0); pixeldata.Write(sprite.Raw, y * sprite.W, sprite.W); } pixeldata.Position = 0; MemoryStream compressedPixels = new MemoryStream(); compressedPixels.WriteByte(0x78); compressedPixels.WriteByte(0x5E); var c = new System.IO.Compression.DeflateStream(compressedPixels, System.IO.Compression.CompressionMode.Compress, true); pixeldata.CopyTo(c); c.Close(); compressedPixels.Position = 0; // IDAT w.Write(toBE((int)compressedPixels.Length)); pos = ms.Position; w.Write(0x54414449); compressedPixels.CopyTo(ms); w.Write(toBE(CRC(ms, pos, ms.Position))); // IEND w.Write(0); w.Write(0x444E4549); w.Write(0x826042AE); ms.Position = 0; ms.CopyTo(fs); fs.Close(); }