ENetChannel.cs 1.5 KB

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