HttpResponse.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. //------------------------------------------------------------------------------
  2. // 此代码版权(除特别声明或在XREF结尾的命名空间的代码)归作者本人若汝棋茗所有
  3. // 源代码使用协议遵循本仓库的开源协议及附加协议,若本仓库没有设置,则按MIT开源协议授权
  4. // CSDN博客:https://blog.csdn.net/qq_40374647
  5. // 哔哩哔哩视频:https://space.bilibili.com/94253567
  6. // Gitee源代码仓库:https://gitee.com/RRQM_Home
  7. // Github源代码仓库:https://github.com/RRQM
  8. // API首页:https://www.yuque.com/rrqm/touchsocket/index
  9. // 交流QQ群:234762506
  10. // 感谢您的下载和使用
  11. //------------------------------------------------------------------------------
  12. //------------------------------------------------------------------------------
  13. using System;
  14. using System.Linq;
  15. using System.Text;
  16. using System.Text.RegularExpressions;
  17. using TouchSocket.Core;
  18. using TouchSocket.Sockets;
  19. namespace TouchSocket.Http
  20. {
  21. /// <summary>
  22. /// Http响应
  23. /// </summary>
  24. public class HttpResponse : HttpBase
  25. {
  26. private bool m_canRead;
  27. private bool m_canWrite;
  28. private ITcpClientBase m_client;
  29. private byte[] m_content;
  30. private bool m_responsed;
  31. private bool m_sentHeader;
  32. private long m_sentLength;
  33. /// <summary>
  34. /// 构造函数
  35. /// </summary>
  36. /// <param name="client"></param>
  37. /// <param name="isServer"></param>
  38. public HttpResponse(ITcpClientBase client, bool isServer = true)
  39. {
  40. m_client = client;
  41. if (isServer)
  42. {
  43. m_canRead = false;
  44. m_canWrite = true;
  45. }
  46. else
  47. {
  48. m_canRead = true;
  49. m_canWrite = false;
  50. }
  51. }
  52. /// <summary>
  53. /// 构造函数
  54. /// </summary>
  55. public HttpResponse()
  56. {
  57. m_canRead = false;
  58. m_canWrite = false;
  59. }
  60. /// <summary>
  61. /// <inheritdoc/>
  62. /// </summary>
  63. public override bool CanRead => m_canRead;
  64. /// <summary>
  65. /// <inheritdoc/>
  66. /// </summary>
  67. public override bool CanWrite => m_canWrite;
  68. /// <summary>
  69. /// <inheritdoc/>
  70. /// </summary>
  71. public override ITcpClientBase Client => m_client;
  72. /// <summary>
  73. /// 关闭会话请求
  74. /// </summary>
  75. public bool CloseConnection
  76. {
  77. get
  78. {
  79. return GetHeader(HttpHeaders.Connection).Equals("close", StringComparison.CurrentCultureIgnoreCase);
  80. }
  81. }
  82. /// <summary>
  83. /// 是否分块
  84. /// </summary>
  85. public bool IsChunk { get; set; }
  86. /// <summary>
  87. /// 是否代理权限验证。
  88. /// </summary>
  89. public bool IsProxyAuthenticationRequired
  90. {
  91. get
  92. {
  93. return StatusCode == "407";
  94. }
  95. }
  96. /// <summary>
  97. /// 是否重定向
  98. /// </summary>
  99. public bool IsRedirect
  100. {
  101. get
  102. {
  103. return StatusCode == "301" || StatusCode == "302";
  104. }
  105. }
  106. /// <summary>
  107. /// 是否已经响应数据。
  108. /// </summary>
  109. public bool Responsed => m_responsed;
  110. /// <summary>
  111. /// 状态码,默认200
  112. /// </summary>
  113. public string StatusCode { get; set; } = "200";
  114. /// <summary>
  115. /// 状态消息,默认Success
  116. /// </summary>
  117. public string StatusMessage { get; set; } = "Success";
  118. /// <summary>
  119. /// 构建数据并回应。
  120. /// <para>该方法仅在具有Client实例时有效。</para>
  121. /// </summary>
  122. public void Answer()
  123. {
  124. if (m_responsed)
  125. {
  126. return;
  127. }
  128. using (ByteBlock byteBlock = new ByteBlock())
  129. {
  130. Build(byteBlock);
  131. if (m_client.CanSend)
  132. {
  133. m_client.DefaultSend(byteBlock);
  134. }
  135. m_responsed = true;
  136. }
  137. }
  138. /// <summary>
  139. /// 构建响应数据。
  140. /// <para>当数据较大时,不建议这样操作,可直接<see cref="WriteContent(byte[], int, int)"/></para>
  141. /// </summary>
  142. /// <param name="byteBlock"></param>
  143. /// <param name="responsed"></param>
  144. public void Build(ByteBlock byteBlock, bool responsed = true)
  145. {
  146. if (m_responsed)
  147. {
  148. throw new Exception("该对象已被响应。");
  149. }
  150. BuildHeader(byteBlock);
  151. BuildContent(byteBlock);
  152. m_responsed = responsed;
  153. }
  154. /// <summary>
  155. /// 构建数据为字节数组。
  156. /// </summary>
  157. /// <returns></returns>
  158. public byte[] BuildAsBytes()
  159. {
  160. using (ByteBlock byteBlock = new ByteBlock())
  161. {
  162. Build(byteBlock);
  163. return byteBlock.ToArray();
  164. }
  165. }
  166. /// <summary>
  167. /// 当传输模式是Chunk时,用于结束传输。
  168. /// </summary>
  169. public void Complete()
  170. {
  171. m_canWrite = false;
  172. if (IsChunk)
  173. {
  174. using (ByteBlock byteBlock = new ByteBlock())
  175. {
  176. byteBlock.Write(Encoding.UTF8.GetBytes($"{0:X}\r\n"));
  177. byteBlock.Write(Encoding.UTF8.GetBytes("\r\n"));
  178. m_client.DefaultSend(byteBlock);
  179. m_responsed = true;
  180. }
  181. }
  182. }
  183. /// <summary>
  184. /// <inheritdoc/>
  185. /// </summary>
  186. /// <param name="content"></param>
  187. public override void SetContent(byte[] content)
  188. {
  189. m_content = content;
  190. ContentLength = content.Length;
  191. ContentComplated = true;
  192. }
  193. /// <summary>
  194. /// <inheritdoc/>
  195. /// </summary>
  196. /// <returns></returns>
  197. public override bool TryGetContent(out byte[] content)
  198. {
  199. if (!ContentComplated.HasValue)
  200. {
  201. if (!IsChunk && m_contentLength == 0)
  202. {
  203. m_content = new byte[0];
  204. content = m_content;
  205. return true;
  206. }
  207. try
  208. {
  209. using (ByteBlock block1 = new ByteBlock(1024 * 1024))
  210. {
  211. using (ByteBlock block2 = new ByteBlock())
  212. {
  213. byte[] buffer = block2.Buffer;
  214. while (true)
  215. {
  216. int r = Read(buffer, 0, buffer.Length);
  217. if (r == 0)
  218. {
  219. break;
  220. }
  221. block1.Write(buffer, 0, r);
  222. }
  223. ContentComplated = true;
  224. m_content = block1.ToArray();
  225. content = m_content;
  226. return true;
  227. }
  228. }
  229. }
  230. catch
  231. {
  232. ContentComplated = false;
  233. content = null;
  234. return false;
  235. }
  236. finally
  237. {
  238. m_canRead = false;
  239. }
  240. }
  241. else if (ContentComplated == true)
  242. {
  243. content = m_content;
  244. return true;
  245. }
  246. else
  247. {
  248. content = null;
  249. return false;
  250. }
  251. }
  252. /// <summary>
  253. /// <inheritdoc/>
  254. /// </summary>
  255. /// <param name="buffer"></param>
  256. /// <param name="offset"></param>
  257. /// <param name="count"></param>
  258. public override void WriteContent(byte[] buffer, int offset, int count)
  259. {
  260. if (m_responsed)
  261. {
  262. throw new Exception("该对象已被响应。");
  263. }
  264. if (!CanWrite)
  265. {
  266. throw new NotSupportedException("该对象不支持持续写入内容。");
  267. }
  268. if (!m_sentHeader)
  269. {
  270. using (ByteBlock byteBlock = new ByteBlock())
  271. {
  272. BuildHeader(byteBlock);
  273. m_client.DefaultSend(byteBlock);
  274. }
  275. m_sentHeader = true;
  276. }
  277. if (IsChunk)
  278. {
  279. using (ByteBlock byteBlock = new ByteBlock(count + 1024))
  280. {
  281. byteBlock.Write(Encoding.UTF8.GetBytes($"{count.ToString("X")}\r\n"));
  282. byteBlock.Write(buffer, offset, count);
  283. byteBlock.Write(Encoding.UTF8.GetBytes("\r\n"));
  284. m_client.DefaultSend(byteBlock);
  285. m_sentLength += count;
  286. }
  287. }
  288. else
  289. {
  290. if (m_sentLength + count <= m_contentLength)
  291. {
  292. m_client.DefaultSend(buffer, offset, count);
  293. m_sentLength += count;
  294. if (m_sentLength == ContentLength)
  295. {
  296. m_canWrite = false;
  297. m_responsed = true;
  298. }
  299. }
  300. }
  301. }
  302. /// <summary>
  303. /// <inheritdoc/>
  304. /// </summary>
  305. /// <param name="disposing"></param>
  306. protected override void Dispose(bool disposing)
  307. {
  308. m_client = null;
  309. base.Dispose(disposing);
  310. }
  311. /// <summary>
  312. /// 读取数据
  313. /// </summary>
  314. protected override void LoadHeaderProterties()
  315. {
  316. var first = Regex.Split(RequestLine, @"(\s+)").Where(e => e.Trim() != string.Empty).ToArray();
  317. if (first.Length > 0)
  318. {
  319. string[] ps = first[0].Split('/');
  320. if (ps.Length == 2)
  321. {
  322. Protocols = ps[0];
  323. ProtocolVersion = ps[1];
  324. }
  325. }
  326. if (first.Length > 1)
  327. {
  328. StatusCode = first[1];
  329. }
  330. string msg = string.Empty;
  331. for (int i = 2; i < first.Length; i++)
  332. {
  333. msg += first[i] + " ";
  334. }
  335. StatusMessage = msg;
  336. string transferEncoding = GetHeader(HttpHeaders.TransferEncoding);
  337. if ("chunked".Equals(transferEncoding, StringComparison.OrdinalIgnoreCase))
  338. {
  339. IsChunk = true;
  340. }
  341. }
  342. private void BuildContent(ByteBlock byteBlock)
  343. {
  344. if (ContentLength > 0)
  345. {
  346. byteBlock.Write(m_content);
  347. }
  348. }
  349. /// <summary>
  350. /// 构建响应头部
  351. /// </summary>
  352. /// <returns></returns>
  353. private void BuildHeader(ByteBlock byteBlock)
  354. {
  355. StringBuilder stringBuilder = new StringBuilder();
  356. stringBuilder.Append($"HTTP/{ProtocolVersion} {StatusCode} {StatusMessage}\r\n");
  357. if (ContentLength > 0)
  358. {
  359. this.SetHeader(HttpHeaders.ContentLength, ContentLength.ToString());
  360. }
  361. if (IsChunk)
  362. {
  363. this.SetHeader(HttpHeaders.TransferEncoding, "chunked");
  364. }
  365. foreach (var headerkey in Headers.AllKeys)
  366. {
  367. stringBuilder.Append($"{headerkey}: ");
  368. stringBuilder.Append(Headers[headerkey] + "\r\n");
  369. }
  370. stringBuilder.Append("\r\n");
  371. byteBlock.Write(Encoding.UTF8.GetBytes(stringBuilder.ToString()));
  372. }
  373. }
  374. }