TcpChannel.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Net.Sockets;
  3. using System.Threading.Tasks;
  4. using BossBase;
  5. using Helper;
  6. using Logger;
  7. namespace BossClient
  8. {
  9. public class TcpChannel: IMessageChannel
  10. {
  11. private readonly NetworkStream networkStream;
  12. public TcpChannel(TcpClient tcpClient)
  13. {
  14. this.networkStream = tcpClient.GetStream();
  15. }
  16. public void Dispose()
  17. {
  18. this.networkStream.Dispose();
  19. }
  20. public async void SendMessage<T>(ushort opcode, T message, byte channelID = 0)
  21. {
  22. byte[] protoBytes = ProtobufHelper.ToBytes(message);
  23. var neworkBytes = new byte[sizeof(int) + sizeof(ushort) + protoBytes.Length];
  24. int totalSize = sizeof(ushort) + protoBytes.Length;
  25. var totalSizeBytes = BitConverter.GetBytes(totalSize);
  26. totalSizeBytes.CopyTo(neworkBytes, 0);
  27. var opcodeBytes = BitConverter.GetBytes(opcode);
  28. opcodeBytes.CopyTo(neworkBytes, sizeof(int));
  29. protoBytes.CopyTo(neworkBytes, sizeof(int) + sizeof(ushort));
  30. await this.networkStream.WriteAsync(neworkBytes, 0, neworkBytes.Length);
  31. }
  32. public async Task<Tuple<ushort, byte[]>> RecvMessage()
  33. {
  34. int totalReadSize = 0;
  35. int needReadSize = sizeof(int);
  36. var packetBytes = new byte[needReadSize];
  37. while (totalReadSize != needReadSize)
  38. {
  39. int readSize = await this.networkStream.ReadAsync(
  40. packetBytes, totalReadSize, packetBytes.Length);
  41. if (readSize == 0)
  42. {
  43. throw new BossException("connection closed");
  44. }
  45. totalReadSize += readSize;
  46. }
  47. int packetSize = BitConverter.ToInt32(packetBytes, 0);
  48. Log.Debug("packetSize: {0}", packetSize);
  49. // 读opcode和message
  50. totalReadSize = 0;
  51. needReadSize = packetSize;
  52. var contentBytes = new byte[needReadSize];
  53. while (totalReadSize != needReadSize)
  54. {
  55. int readSize = await this.networkStream.ReadAsync(
  56. contentBytes, totalReadSize, contentBytes.Length);
  57. if (readSize == 0)
  58. {
  59. throw new BossException("connection closed");
  60. }
  61. totalReadSize += readSize;
  62. }
  63. ushort opcode = BitConverter.ToUInt16(contentBytes, 0);
  64. var messageBytes = new byte[needReadSize - sizeof(ushort)];
  65. Array.Copy(contentBytes, sizeof(ushort), messageBytes, 0, messageBytes.Length);
  66. return Tuple.Create(opcode, messageBytes);
  67. }
  68. }
  69. }