ENetChannel.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Threading.Tasks;
  3. using BossBase;
  4. using ENet;
  5. using Helper;
  6. using Ionic.Zlib;
  7. namespace BossClient
  8. {
  9. class ENetChannel: IMessageChannel
  10. {
  11. private readonly ESocket eSocket;
  12. public ENetChannel(ESocket eSocket)
  13. {
  14. this.eSocket = eSocket;
  15. }
  16. public async void Dispose()
  17. {
  18. await this.eSocket.DisconnectLaterAsync();
  19. this.eSocket.Dispose();
  20. }
  21. public void SendMessage<T>(ushort opcode, T message, byte channelID = 0)
  22. {
  23. byte[] protoBytes = ProtobufHelper.ToBytes(message);
  24. var neworkBytes = new byte[sizeof(ushort) + protoBytes.Length];
  25. var opcodeBytes = BitConverter.GetBytes(opcode);
  26. opcodeBytes.CopyTo(neworkBytes, 0);
  27. protoBytes.CopyTo(neworkBytes, sizeof(ushort));
  28. this.eSocket.WriteAsync(neworkBytes, channelID);
  29. }
  30. public async Task<Tuple<ushort, byte[]>> RecvMessage()
  31. {
  32. var bytes = await this.eSocket.ReadAsync();
  33. const int opcodeSize = sizeof(ushort);
  34. ushort opcode = BitConverter.ToUInt16(bytes, 0);
  35. byte flag = bytes[2];
  36. if (flag == 0)
  37. {
  38. var messageBytes = new byte[bytes.Length - opcodeSize - 1];
  39. Array.Copy(bytes, opcodeSize + 1, messageBytes, 0, messageBytes.Length);
  40. return Tuple.Create(opcode, messageBytes);
  41. }
  42. else
  43. {
  44. var messageBytes = new byte[bytes.Length - opcodeSize - 5];
  45. Array.Copy(bytes, opcodeSize + 5, messageBytes, 0, messageBytes.Length);
  46. messageBytes = ZlibStream.UncompressBuffer(messageBytes);
  47. return Tuple.Create(opcode, messageBytes);
  48. }
  49. }
  50. }
  51. }