ENetChannel.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. namespace LoginClient
  9. {
  10. class ENetChannel: IMessageChannel
  11. {
  12. private readonly Peer peer;
  13. public ENetChannel(Peer peer)
  14. {
  15. this.peer = peer;
  16. }
  17. public async void Dispose()
  18. {
  19. await this.peer.DisconnectLaterAsync();
  20. this.peer.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.peer.WriteAsync(channelID, neworkBytes);
  30. }
  31. public async Task<Tuple<ushort, byte[]>> RecvMessage()
  32. {
  33. using (Packet packet = await this.peer.ReadAsync())
  34. {
  35. byte[] bytes = packet.Bytes;
  36. const int opcodeSize = sizeof(ushort);
  37. ushort opcode = BitConverter.ToUInt16(bytes, 0);
  38. var messageBytes = new byte[packet.Length - opcodeSize];
  39. Array.Copy(bytes, opcodeSize, messageBytes, 0, messageBytes.Length);
  40. return Tuple.Create(opcode, messageBytes);
  41. }
  42. }
  43. }
  44. }