You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

MessageWriter.cs 2.0 kB

2 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using Google.Protobuf;
  2. using Protobuf;
  3. using System;
  4. using System.IO;
  5. using System.IO.Compression;
  6. namespace Playback
  7. {
  8. public class MessageWriter : IDisposable
  9. {
  10. private FileStream fs;
  11. private CodedOutputStream cos;
  12. private MemoryStream ms;
  13. private GZipStream gzs;
  14. private const int memoryCapacity = 1024 * 1024; // 1M
  15. private static void ClearMemoryStream(MemoryStream msToClear)
  16. {
  17. msToClear.Position = 0;
  18. msToClear.SetLength(0);
  19. }
  20. public MessageWriter(string fileName, uint teamCount, uint playerCount)
  21. {
  22. if (!fileName.EndsWith(PlayBackConstant.ExtendedName))
  23. {
  24. fileName += PlayBackConstant.ExtendedName;
  25. }
  26. fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
  27. fs.Write(PlayBackConstant.Prefix); // 写入前缀
  28. fs.Write(BitConverter.GetBytes((UInt32)teamCount)); // 写入队伍数
  29. fs.Write(BitConverter.GetBytes((UInt32)playerCount)); // 写入每队的玩家人数
  30. ms = new MemoryStream(memoryCapacity);
  31. cos = new CodedOutputStream(ms);
  32. gzs = new GZipStream(fs, CompressionMode.Compress);
  33. }
  34. public void WriteOne(MessageToClient msg)
  35. {
  36. cos.WriteMessage(msg);
  37. if (ms.Length > memoryCapacity)
  38. Flush();
  39. }
  40. public void Flush()
  41. {
  42. if (fs.CanWrite)
  43. {
  44. cos.Flush();
  45. gzs.Write(ms.GetBuffer(), 0, (int)ms.Length);
  46. ClearMemoryStream(ms);
  47. fs.Flush();
  48. }
  49. }
  50. public void Dispose()
  51. {
  52. if (fs.CanWrite)
  53. {
  54. Flush();
  55. cos.Dispose();
  56. gzs.Dispose();
  57. fs.Dispose();
  58. }
  59. }
  60. ~MessageWriter()
  61. {
  62. Dispose();
  63. }
  64. }
  65. }