TcpChannel.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 =
  40. await
  41. this.networkStream.ReadAsync(packetBytes, totalReadSize,
  42. packetBytes.Length);
  43. if (readSize == 0)
  44. {
  45. throw new BossException("connection closed");
  46. }
  47. totalReadSize += readSize;
  48. }
  49. int packetSize = BitConverter.ToInt32(packetBytes, 0);
  50. Log.Debug("packetSize: {0}", packetSize);
  51. // 读opcode和message
  52. totalReadSize = 0;
  53. needReadSize = packetSize;
  54. var contentBytes = new byte[needReadSize];
  55. while (totalReadSize != needReadSize)
  56. {
  57. int readSize =
  58. await
  59. this.networkStream.ReadAsync(contentBytes, totalReadSize,
  60. contentBytes.Length);
  61. if (readSize == 0)
  62. {
  63. throw new BossException("connection closed");
  64. }
  65. totalReadSize += readSize;
  66. }
  67. ushort opcode = BitConverter.ToUInt16(contentBytes, 0);
  68. var messageBytes = new byte[needReadSize - sizeof (ushort)];
  69. Array.Copy(contentBytes, sizeof (ushort), messageBytes, 0, messageBytes.Length);
  70. return Tuple.Create(opcode, messageBytes);
  71. }
  72. }
  73. }