ENetChannel.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. using BossBase;
  5. using ENet;
  6. using Helper;
  7. using System.IO.Compression;
  8. namespace BossClient
  9. {
  10. 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 (var zipStream = new GZipStream(
  49. new MemoryStream(bytes, opcodeSize + 5, bytes.Length - opcodeSize - 5),
  50. CompressionMode.Decompress))
  51. {
  52. zipStream.CopyTo(decompressStream);
  53. }
  54. var decompressBytes = decompressStream.ToArray();
  55. return Tuple.Create(opcode, decompressBytes);
  56. }
  57. }
  58. }
  59. }
  60. }