ENetChannel.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 Peer peer;
  12. public ENetChannel(Peer peer)
  13. {
  14. this.peer = peer;
  15. }
  16. public async void Dispose()
  17. {
  18. await this.peer.DisconnectLaterAsync();
  19. this.peer.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.peer.WriteAsync(channelID, neworkBytes);
  29. }
  30. public async Task<Tuple<ushort, byte[]>> RecvMessage()
  31. {
  32. using (Packet packet = await this.peer.ReadAsync())
  33. {
  34. byte[] bytes = packet.Bytes;
  35. const int opcodeSize = sizeof(ushort);
  36. ushort opcode = BitConverter.ToUInt16(bytes, 0);
  37. byte flag = bytes[2];
  38. if (flag == 0)
  39. {
  40. var messageBytes = new byte[packet.Length - opcodeSize - 1];
  41. Array.Copy(bytes, opcodeSize + 1, messageBytes, 0, messageBytes.Length);
  42. return Tuple.Create(opcode, messageBytes);
  43. }
  44. else
  45. {
  46. var messageBytes = new byte[packet.Length - opcodeSize - 5];
  47. Array.Copy(bytes, opcodeSize + 5, messageBytes, 0, messageBytes.Length);
  48. messageBytes = ZlibStream.UncompressBuffer(messageBytes);
  49. return Tuple.Create(opcode, messageBytes);
  50. }
  51. }
  52. }
  53. }
  54. }