ENetChannel.cs 1.5 KB

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