ENetChannel.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.IO;
  3. using System.IO.Compression;
  4. using System.Threading.Tasks;
  5. using BossBase;
  6. using ENet;
  7. using Helper;
  8. namespace BossClient
  9. {
  10. internal class ENetChannel: IMessageChannel
  11. {
  12. private readonly ESocket eSocket;
  13. public ENetChannel(ESocket eSocket)
  14. {
  15. this.eSocket = eSocket;
  16. }
  17. public async void Dispose()
  18. {
  19. await this.eSocket.DisconnectLaterAsync();
  20. this.eSocket.Dispose();
  21. }
  22. public void SendMessage<T>(ushort opcode, T message, byte channelID = 0)
  23. {
  24. byte[] protoBytes = ProtobufHelper.ToBytes(message);
  25. var neworkBytes = new byte[sizeof (ushort) + protoBytes.Length];
  26. var opcodeBytes = BitConverter.GetBytes(opcode);
  27. opcodeBytes.CopyTo(neworkBytes, 0);
  28. protoBytes.CopyTo(neworkBytes, sizeof (ushort));
  29. this.eSocket.WriteAsync(neworkBytes, channelID);
  30. }
  31. public async Task<Tuple<ushort, byte[]>> RecvMessage()
  32. {
  33. var bytes = await this.eSocket.ReadAsync();
  34. const int opcodeSize = sizeof (ushort);
  35. ushort opcode = BitConverter.ToUInt16(bytes, 0);
  36. byte flag = bytes[2];
  37. switch (flag)
  38. {
  39. case 0:
  40. {
  41. var messageBytes = new byte[bytes.Length - opcodeSize - 1];
  42. Array.Copy(bytes, opcodeSize + 1, messageBytes, 0, messageBytes.Length);
  43. return Tuple.Create(opcode, messageBytes);
  44. }
  45. default:
  46. {
  47. var decompressStream = new MemoryStream();
  48. using (
  49. var zipStream =
  50. new GZipStream(
  51. new MemoryStream(bytes, opcodeSize + 5,
  52. bytes.Length - opcodeSize - 5),
  53. CompressionMode.Decompress))
  54. {
  55. zipStream.CopyTo(decompressStream);
  56. }
  57. var decompressBytes = decompressStream.ToArray();
  58. return Tuple.Create(opcode, decompressBytes);
  59. }
  60. }
  61. }
  62. }
  63. }