TcpStreamHelper.cs 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. namespace Azylee.YeahWeb.SocketUtils.TcpUtils
  7. {
  8. /// <summary>
  9. /// Tcp 流数据处理辅助类
  10. /// </summary>
  11. public class TcpStreamHelper
  12. {
  13. const int ReceiveBufferSize = 1024;
  14. /// <summary>
  15. /// 流 写入
  16. /// </summary>
  17. /// <param name="stream"></param>
  18. /// <param name="model"></param>
  19. /// <returns></returns>
  20. public static bool Write(TcpClient client, TcpDataModel model)
  21. {
  22. try
  23. {
  24. if (client != null && client.GetStream() != null)
  25. {
  26. byte[] md_byte = model.ToByte();
  27. byte[] length_byte = BitConverter.GetBytes((int)(md_byte.Length + 4));
  28. List<byte> data = new List<byte>();
  29. data.AddRange(length_byte);//长度
  30. data.AddRange(new byte[] { 111, 222, 66, 66 });//标志
  31. data.AddRange(md_byte);//内容
  32. client.GetStream().Write(data.ToArray(), 0, data.Count);//写出内容
  33. return true;
  34. }
  35. }
  36. catch { }
  37. return false;
  38. }
  39. /// <summary>
  40. /// 流 读取
  41. /// </summary>
  42. /// <param name="stream"></param>
  43. /// <returns></returns>
  44. public static TcpDataModel Read(TcpClient client)
  45. {
  46. TcpDataModel data = null;
  47. try
  48. {
  49. if (client != null && client.GetStream() != null)
  50. {
  51. //内容长度
  52. byte[] data_length = new byte[4];
  53. int read = client.GetStream().Read(data_length, 0, 4);
  54. int length = BitConverter.ToInt32(data_length, 0) - 4;
  55. if (read > 0 && length > 0)
  56. {
  57. //内容头部标志
  58. byte[] data_head = new byte[4];
  59. client.GetStream().Read(data_head, 0, 4);
  60. bool head = data_head[0] == 111 && data_head[1] == 222 && data_head[2] == 66 && data_head[3] == 66;
  61. if (head)
  62. {
  63. //读取内容
  64. byte[] buffer = new byte[length];
  65. int bf_read = 0;
  66. while (bf_read < length)
  67. {
  68. //循环读取内容,防止断包
  69. bf_read += client.GetStream().Read(buffer, bf_read, length - bf_read);
  70. if (bf_read < length)
  71. {
  72. int x = bf_read;
  73. }
  74. }
  75. //解析内容
  76. data = TcpDataModel.ToModel(buffer);
  77. }
  78. }
  79. else
  80. {
  81. if (read == 0)
  82. client?.Close();
  83. }
  84. }
  85. }
  86. catch { }
  87. return data;
  88. }
  89. }
  90. }