SocketClient.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  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.Collections.Generic;
  15. using System.Diagnostics;
  16. using System.IO;
  17. using System.Net.Security;
  18. using System.Net.Sockets;
  19. using System.Threading.Tasks;
  20. using TouchSocket.Core;
  21. using TouchSocket.Resources;
  22. namespace TouchSocket.Sockets
  23. {
  24. /// <summary>
  25. /// 服务器辅助类
  26. /// </summary>
  27. [DebuggerDisplay("ID={ID},IPAdress={IP}:{Port}")]
  28. public class SocketClient : BaseSocket, ISocketClient
  29. {
  30. /// <summary>
  31. /// 构造函数
  32. /// </summary>
  33. public SocketClient()
  34. {
  35. Protocol = Protocol.TCP;
  36. }
  37. #region 变量
  38. internal string m_id;
  39. internal ReceiveType m_receiveType;
  40. internal TcpServiceBase m_service;
  41. internal bool m_usePlugin;
  42. private DataHandlingAdapter m_adapter;
  43. private DelaySender m_delaySender;
  44. private Socket m_mainSocket;
  45. //private int m_maxPackageSize;
  46. private bool m_online;
  47. private bool m_useDelaySender;
  48. private Stream m_workStream;
  49. #endregion 变量
  50. #region 属性
  51. /// <inheritdoc/>
  52. public bool IsClient => false;
  53. /// <summary>
  54. /// <inheritdoc/>
  55. /// </summary>
  56. public bool CanSend => m_online;
  57. /// <summary>
  58. /// <inheritdoc/>
  59. /// </summary>
  60. public virtual bool CanSetDataHandlingAdapter => true;
  61. /// <summary>
  62. /// <inheritdoc/>
  63. /// </summary>
  64. public TouchSocketConfig Config { get; internal set; }
  65. /// <summary>
  66. /// <inheritdoc/>
  67. /// </summary>
  68. public IContainer Container => Config?.Container;
  69. /// <summary>
  70. /// <inheritdoc/>
  71. /// </summary>
  72. public DataHandlingAdapter DataHandlingAdapter => m_adapter;
  73. /// <summary>
  74. /// 用于索引的ID
  75. /// </summary>
  76. public string ID => m_id;
  77. /// <summary>
  78. /// <inheritdoc/>
  79. /// </summary>
  80. public string IP { get; private set; }
  81. /// <summary>
  82. /// <inheritdoc/>
  83. /// </summary>
  84. public Socket MainSocket => m_mainSocket;
  85. /// <summary>
  86. /// <inheritdoc/>
  87. /// </summary>
  88. public bool Online => m_online;
  89. /// <summary>
  90. /// <inheritdoc/>
  91. /// </summary>
  92. public IPluginsManager PluginsManager => Config?.PluginsManager;
  93. /// <summary>
  94. /// <inheritdoc/>
  95. /// </summary>
  96. public int Port { get; private set; }
  97. /// <summary>
  98. /// <inheritdoc/>
  99. /// </summary>
  100. public Protocol Protocol { get; set; }
  101. /// <summary>
  102. /// <inheritdoc/>
  103. /// </summary>
  104. public ReceiveType ReceiveType => m_receiveType;
  105. /// <summary>
  106. /// <inheritdoc/>
  107. /// </summary>
  108. public TcpServiceBase Service => m_service;
  109. /// <summary>
  110. /// <inheritdoc/>
  111. /// </summary>
  112. public bool UsePlugin => m_usePlugin;
  113. /// <summary>
  114. /// <inheritdoc/>
  115. /// </summary>
  116. public bool UseSsl { get; private set; }
  117. #endregion 属性
  118. #region 事件&委托
  119. /// <summary>
  120. /// <inheritdoc/>
  121. /// </summary>
  122. public DisconnectEventHandler<ITcpClientBase> Disconnected { get; set; }
  123. /// <summary>
  124. /// <inheritdoc/>
  125. /// </summary>
  126. public DisconnectEventHandler<ITcpClientBase> Disconnecting { get; set; }
  127. /// <summary>
  128. /// 即将断开连接(仅主动断开时有效)。
  129. /// <para>
  130. /// 当主动调用Close断开时,可通过<see cref="TouchSocketEventArgs.IsPermitOperation"/>终止断开行为。
  131. /// </para>
  132. /// </summary>
  133. /// <param name="e"></param>
  134. protected virtual void OnDisconnecting(DisconnectEventArgs e)
  135. {
  136. try
  137. {
  138. Disconnecting?.Invoke(this, e);
  139. }
  140. catch (Exception ex)
  141. {
  142. Logger.Log(LogType.Error, this, $"在事件{nameof(Disconnecting)}中发生错误。", ex);
  143. }
  144. }
  145. /// <summary>
  146. /// 当客户端完整建立TCP连接,如果覆盖父类方法,则不会触发插件。
  147. /// </summary>
  148. /// <param name="e"></param>
  149. protected virtual void OnConnected(TouchSocketEventArgs e)
  150. {
  151. m_service.OnInternalConnected(this, e);
  152. }
  153. /// <summary>
  154. /// 客户端正在连接,如果覆盖父类方法,则不会触发插件。
  155. /// </summary>
  156. protected virtual void OnConnecting(OperationEventArgs e)
  157. {
  158. m_service.OnInternalConnecting(this, e);
  159. }
  160. /// <summary>
  161. /// 在延迟发生错误
  162. /// </summary>
  163. /// <param name="ex"></param>
  164. protected virtual void OnDelaySenderError(Exception ex)
  165. {
  166. Logger.Log(LogType.Error, this, "发送错误", ex);
  167. }
  168. /// <summary>
  169. /// 客户端已断开连接,如果从Connecting中拒绝连接,则不会触发。如果覆盖父类方法,则不会触发插件。
  170. /// </summary>
  171. /// <param name="e"></param>
  172. protected virtual void OnDisconnected(DisconnectEventArgs e)
  173. {
  174. Disconnected?.Invoke(this, e);
  175. }
  176. /// <summary>
  177. /// 当初始化完成时,执行在<see cref="OnConnecting(OperationEventArgs)"/>之前。
  178. /// </summary>
  179. protected virtual void OnInitialized()
  180. {
  181. }
  182. private void PrivateOnDisconnected(DisconnectEventArgs e)
  183. {
  184. if (m_usePlugin && PluginsManager.Raise<IDisconnectedPlguin>(nameof(IDisconnectedPlguin.OnDisconnected), this, e))
  185. {
  186. return;
  187. }
  188. OnDisconnected(e);
  189. if (!e.Handled)
  190. {
  191. m_service.OnInternalDisconnected(this, e);
  192. }
  193. }
  194. private void PrivateOnDisconnecting(DisconnectEventArgs e)
  195. {
  196. if (m_usePlugin && PluginsManager.Raise<IDisconnectingPlugin>(nameof(IDisconnectingPlugin.OnDisconnecting), this, e))
  197. {
  198. return;
  199. }
  200. OnDisconnecting(e);
  201. if (!e.Handled)
  202. {
  203. m_service.OnInternalDisconnecting(this, e);
  204. }
  205. }
  206. #endregion 事件&委托
  207. /// <summary>
  208. /// <inheritdoc/>
  209. /// </summary>
  210. public DateTime LastReceivedTime { get; private set; }
  211. /// <summary>
  212. /// <inheritdoc/>
  213. /// </summary>
  214. public DateTime LastSendTime { get; private set; }
  215. /// <summary>
  216. /// <inheritdoc/>
  217. /// </summary>
  218. public Func<ByteBlock, bool> OnHandleRawBuffer { get; set; }
  219. /// <summary>
  220. ///<inheritdoc/>
  221. /// </summary>
  222. public Func<ByteBlock, IRequestInfo, bool> OnHandleReceivedData { get; set; }
  223. /// <summary>
  224. /// <inheritdoc/>
  225. /// </summary>
  226. public string ServiceIP { get; private set; }
  227. /// <summary>
  228. /// <inheritdoc/>
  229. /// </summary>
  230. public int ServicePort { get; private set; }
  231. /// <inheritdoc/>
  232. public virtual void Close()
  233. {
  234. Close($"主动调用{nameof(Close)}");
  235. }
  236. /// <inheritdoc/>
  237. public virtual void Close(string msg)
  238. {
  239. if (this.m_online)
  240. {
  241. var args = new DisconnectEventArgs(true, msg)
  242. {
  243. IsPermitOperation = true
  244. };
  245. PrivateOnDisconnecting(args);
  246. if (this.DisposedValue || args.IsPermitOperation)
  247. {
  248. BreakOut(msg, true);
  249. }
  250. }
  251. }
  252. /// <summary>
  253. /// <inheritdoc/>
  254. /// </summary>
  255. /// <returns></returns>
  256. public Stream GetStream()
  257. {
  258. if (m_workStream == null)
  259. {
  260. m_workStream = new NetworkStream(m_mainSocket, true);
  261. }
  262. return m_workStream;
  263. }
  264. /// <summary>
  265. /// 直接重置内部ID。
  266. /// </summary>
  267. /// <param name="newId"></param>
  268. protected void DirectResetID(string newId)
  269. {
  270. if (string.IsNullOrEmpty(newId))
  271. {
  272. throw new ArgumentException($"“{nameof(newId)}”不能为 null 或空。", nameof(newId));
  273. }
  274. if (m_id == newId)
  275. {
  276. return;
  277. }
  278. string oldId = m_id;
  279. if (Service.SocketClients.TryRemove(m_id, out SocketClient socketClient))
  280. {
  281. socketClient.m_id = newId;
  282. if (Service.SocketClients.TryAdd(socketClient))
  283. {
  284. if (m_usePlugin)
  285. {
  286. IDChangedEventArgs e = new IDChangedEventArgs(oldId, newId);
  287. PluginsManager.Raise<ITcpPlugin>(nameof(ITcpPlugin.OnIDChanged), socketClient, e);
  288. }
  289. return;
  290. }
  291. else
  292. {
  293. socketClient.m_id = oldId;
  294. if (Service.SocketClients.TryAdd(socketClient))
  295. {
  296. throw new Exception("ID重复");
  297. }
  298. else
  299. {
  300. socketClient.Close("修改新ID时操作失败,且回退旧ID时也失败。");
  301. }
  302. }
  303. }
  304. else
  305. {
  306. throw new ClientNotFindException(TouchSocketStatus.ClientNotFind.GetDescription(oldId));
  307. }
  308. }
  309. /// <summary>
  310. /// <inheritdoc/>
  311. /// </summary>
  312. /// <param name="newId"></param>
  313. /// <exception cref="ArgumentException"></exception>
  314. /// <exception cref="ClientNotFindException"></exception>
  315. /// <exception cref="Exception"></exception>
  316. public virtual void ResetID(string newId)
  317. {
  318. DirectResetID(newId);
  319. }
  320. /// <summary>
  321. /// <inheritdoc/>
  322. /// </summary>
  323. /// <param name="adapter"></param>
  324. public virtual void SetDataHandlingAdapter(DataHandlingAdapter adapter)
  325. {
  326. if (!CanSetDataHandlingAdapter)
  327. {
  328. throw new Exception($"不允许自由调用{nameof(SetDataHandlingAdapter)}进行赋值。");
  329. }
  330. SetAdapter(adapter);
  331. }
  332. internal void BeginReceive(ReceiveType receiveType)
  333. {
  334. try
  335. {
  336. if (receiveType == ReceiveType.Auto)
  337. {
  338. SocketAsyncEventArgs eventArgs = new SocketAsyncEventArgs();
  339. eventArgs.Completed += EventArgs_Completed;
  340. ByteBlock byteBlock = BytePool.Default.GetByteBlock(BufferLength);
  341. eventArgs.UserToken = byteBlock;
  342. eventArgs.SetBuffer(byteBlock.Buffer, 0, byteBlock.Capacity);
  343. if (!m_mainSocket.ReceiveAsync(eventArgs))
  344. {
  345. ProcessReceived(eventArgs);
  346. }
  347. }
  348. }
  349. catch (Exception ex)
  350. {
  351. BreakOut(ex.Message, false);
  352. }
  353. }
  354. internal void BeginReceiveSsl(ReceiveType receiveType, ServiceSslOption sslOption)
  355. {
  356. SslStream sslStream = (sslOption.CertificateValidationCallback != null) ? new SslStream(new NetworkStream(m_mainSocket, false), false, sslOption.CertificateValidationCallback) : new SslStream(new NetworkStream(m_mainSocket, false), false);
  357. sslStream.AuthenticateAsServer(sslOption.Certificate, sslOption.ClientCertificateRequired, sslOption.SslProtocols, sslOption.CheckCertificateRevocation);
  358. m_workStream = sslStream;
  359. UseSsl = true;
  360. if (receiveType == ReceiveType.Auto)
  361. {
  362. BeginSsl();
  363. }
  364. }
  365. internal void InternalConnected(TouchSocketEventArgs e)
  366. {
  367. m_online = true;
  368. if (Config.GetValue<DelaySenderOption>(TouchSocketConfigExtension.DelaySenderProperty) is DelaySenderOption senderOption)
  369. {
  370. m_useDelaySender = true;
  371. m_delaySender.SafeDispose();
  372. m_delaySender = new DelaySender(m_mainSocket, senderOption.QueueLength, OnDelaySenderError)
  373. {
  374. DelayLength = senderOption.DelayLength
  375. };
  376. }
  377. if (m_usePlugin && PluginsManager.Raise<IConnectedPlugin>(nameof(IConnectedPlugin.OnConnected), this, e))
  378. {
  379. return;
  380. }
  381. OnConnected(e);
  382. }
  383. internal void InternalConnecting(OperationEventArgs e)
  384. {
  385. if (m_usePlugin && PluginsManager.Raise<IConnectingPlugin>(nameof(IConnectingPlugin.OnConnecting), this, e))
  386. {
  387. return;
  388. }
  389. OnConnecting(e);
  390. }
  391. internal void InternalInitialized()
  392. {
  393. LastReceivedTime = DateTime.Now;
  394. LastSendTime = DateTime.Now;
  395. OnInitialized();
  396. }
  397. internal void SetSocket(Socket mainSocket)
  398. {
  399. m_mainSocket = mainSocket ?? throw new ArgumentNullException(nameof(mainSocket));
  400. IP = mainSocket.RemoteEndPoint.GetIP();
  401. Port = mainSocket.RemoteEndPoint.GetPort();
  402. ServiceIP = mainSocket.LocalEndPoint.GetIP();
  403. ServicePort = mainSocket.LocalEndPoint.GetPort();
  404. }
  405. /// <summary>
  406. /// <inheritdoc/>
  407. /// </summary>
  408. /// <param name="disposing"></param>
  409. protected override void Dispose(bool disposing)
  410. {
  411. if (this.m_online)
  412. {
  413. var args = new DisconnectEventArgs(true, $"{nameof(Dispose)}主动断开");
  414. PrivateOnDisconnecting(args);
  415. }
  416. m_adapter.SafeDispose();
  417. m_adapter = default;
  418. BreakOut($"{nameof(Dispose)}主动断开", true);
  419. base.Dispose(disposing);
  420. }
  421. /// <summary>
  422. /// 处理已接收到的数据。
  423. /// <para>根据不同的数据处理适配器,会传递不同的数据</para>
  424. /// </summary>
  425. /// <param name="byteBlock">以二进制流形式传递</param>
  426. /// <param name="requestInfo">以解析的数据对象传递</param>
  427. protected virtual void HandleReceivedData(ByteBlock byteBlock, IRequestInfo requestInfo)
  428. {
  429. }
  430. /// <summary>
  431. /// 当即将发送时,如果覆盖父类方法,则不会触发插件。
  432. /// </summary>
  433. /// <param name="buffer">数据缓存区</param>
  434. /// <param name="offset">偏移</param>
  435. /// <param name="length">长度</param>
  436. /// <returns>返回值表示是否允许发送</returns>
  437. protected virtual bool HandleSendingData(byte[] buffer, int offset, int length)
  438. {
  439. if (m_usePlugin)
  440. {
  441. SendingEventArgs args = new SendingEventArgs(buffer, offset, length);
  442. PluginsManager.Raise<ITcpPlugin>(nameof(ITcpPlugin.OnSendingData), this, args);
  443. if (args.IsPermitOperation)
  444. {
  445. return true;
  446. }
  447. return false;
  448. }
  449. return true;
  450. }
  451. /// <summary>
  452. /// 设置适配器,该方法不会检验<see cref="CanSetDataHandlingAdapter"/>的值。
  453. /// </summary>
  454. /// <param name="adapter"></param>
  455. protected void SetAdapter(DataHandlingAdapter adapter)
  456. {
  457. if (adapter is null)
  458. {
  459. throw new ArgumentNullException(nameof(adapter));
  460. }
  461. if (Config != null)
  462. {
  463. if (Config.GetValue(TouchSocketConfigExtension.MaxPackageSizeProperty) is int v1)
  464. {
  465. adapter.MaxPackageSize = v1;
  466. }
  467. if (Config.GetValue(TouchSocketConfigExtension.CacheTimeoutProperty) != TimeSpan.Zero)
  468. {
  469. adapter.CacheTimeout = Config.GetValue(TouchSocketConfigExtension.CacheTimeoutProperty);
  470. }
  471. if (Config.GetValue(TouchSocketConfigExtension.CacheTimeoutEnableProperty) is bool v2)
  472. {
  473. adapter.CacheTimeoutEnable = v2;
  474. }
  475. if (Config.GetValue(TouchSocketConfigExtension.UpdateCacheTimeWhenRevProperty) is bool v3)
  476. {
  477. adapter.UpdateCacheTimeWhenRev = v3;
  478. }
  479. }
  480. adapter.OnLoaded(this);
  481. adapter.ReceivedCallBack = PrivateHandleReceivedData;
  482. adapter.SendCallBack = DefaultSend;
  483. m_adapter = adapter;
  484. }
  485. private void BeginSsl()
  486. {
  487. if (!DisposedValue)
  488. {
  489. ByteBlock byteBlock = new ByteBlock(BufferLength);
  490. try
  491. {
  492. m_workStream.BeginRead(byteBlock.Buffer, 0, byteBlock.Capacity, EndSsl, byteBlock);
  493. }
  494. catch (System.Exception ex)
  495. {
  496. byteBlock.Dispose();
  497. BreakOut(ex.Message, false);
  498. }
  499. }
  500. }
  501. private void BreakOut(string msg, bool manual)
  502. {
  503. lock (this.SyncRoot)
  504. {
  505. if (m_online)
  506. {
  507. m_online = false;
  508. this.TryShutdown();
  509. m_mainSocket.SafeDispose();
  510. m_delaySender.SafeDispose();
  511. m_adapter.SafeDispose();
  512. m_service?.SocketClients.TryRemove(m_id, out _);
  513. PrivateOnDisconnected(new DisconnectEventArgs(manual, msg));
  514. Disconnected = null;
  515. }
  516. base.Dispose(true);
  517. }
  518. }
  519. private void EndSsl(IAsyncResult result)
  520. {
  521. ByteBlock byteBlock = (ByteBlock)result.AsyncState;
  522. try
  523. {
  524. int r = m_workStream.EndRead(result);
  525. if (r == 0)
  526. {
  527. BreakOut("远程终端主动关闭", false);
  528. }
  529. byteBlock.SetLength(r);
  530. HandleBuffer(byteBlock);
  531. BeginSsl();
  532. }
  533. catch (Exception ex)
  534. {
  535. byteBlock.Dispose();
  536. BreakOut(ex.Message, false);
  537. }
  538. }
  539. private void EventArgs_Completed(object sender, SocketAsyncEventArgs e)
  540. {
  541. try
  542. {
  543. ProcessReceived(e);
  544. }
  545. catch (Exception ex)
  546. {
  547. e.SafeDispose();
  548. BreakOut(ex.Message, false);
  549. }
  550. }
  551. private void HandleBuffer(ByteBlock byteBlock)
  552. {
  553. try
  554. {
  555. LastReceivedTime = DateTime.Now;
  556. if (OnHandleRawBuffer?.Invoke(byteBlock) == false)
  557. {
  558. return;
  559. }
  560. if (UsePlugin && PluginsManager.Raise<ITcpPlugin>(nameof(ITcpPlugin.OnReceivingData), this, new ByteBlockEventArgs(byteBlock)))
  561. {
  562. return;
  563. }
  564. if (DisposedValue)
  565. {
  566. return;
  567. }
  568. if (m_adapter == null)
  569. {
  570. Logger.Error(this, TouchSocketStatus.NullDataAdapter.GetDescription());
  571. return;
  572. }
  573. m_adapter.ReceivedInput(byteBlock);
  574. }
  575. catch (System.Exception ex)
  576. {
  577. Logger.Log(LogType.Error, this, "在处理数据时发生错误", ex);
  578. }
  579. finally
  580. {
  581. byteBlock.Dispose();
  582. }
  583. }
  584. private void PrivateHandleReceivedData(ByteBlock byteBlock, IRequestInfo requestInfo)
  585. {
  586. if (OnHandleReceivedData?.Invoke(byteBlock, requestInfo) == false)
  587. {
  588. return;
  589. }
  590. if (m_usePlugin)
  591. {
  592. ReceivedDataEventArgs args = new ReceivedDataEventArgs(byteBlock, requestInfo);
  593. PluginsManager.Raise<ITcpPlugin>(nameof(ITcpPlugin.OnReceivedData), this, args);
  594. if (args.Handled)
  595. {
  596. return;
  597. }
  598. }
  599. HandleReceivedData(byteBlock, requestInfo);
  600. m_service.OnInternalReceivedData(this, byteBlock, requestInfo);
  601. }
  602. private void ProcessReceived(SocketAsyncEventArgs e)
  603. {
  604. if (DisposedValue)
  605. {
  606. e.SafeDispose();
  607. }
  608. else
  609. {
  610. if (e.SocketError == SocketError.Success && e.BytesTransferred > 0)
  611. {
  612. ByteBlock byteBlock = (ByteBlock)e.UserToken;
  613. byteBlock.SetLength(e.BytesTransferred);
  614. HandleBuffer(byteBlock);
  615. try
  616. {
  617. ByteBlock newByteBlock = new ByteBlock(BufferLength);
  618. e.UserToken = newByteBlock;
  619. e.SetBuffer(newByteBlock.Buffer, 0, newByteBlock.Capacity);
  620. if (!m_mainSocket.ReceiveAsync(e))
  621. {
  622. ProcessReceived(e);
  623. }
  624. }
  625. catch (Exception ex)
  626. {
  627. BreakOut(ex.Message, false);
  628. }
  629. }
  630. else
  631. {
  632. e.SafeDispose();
  633. BreakOut("远程主机主动断开连接", false);
  634. }
  635. }
  636. }
  637. #region 发送
  638. /// <summary>
  639. /// <inheritdoc/>
  640. /// </summary>
  641. /// <param name="buffer"></param>
  642. /// <param name="offset"></param>
  643. /// <param name="length"></param>
  644. /// <exception cref="NotConnectedException"></exception>
  645. /// <exception cref="OverlengthException"></exception>
  646. /// <exception cref="Exception"></exception>
  647. public void DefaultSend(byte[] buffer, int offset, int length)
  648. {
  649. if (!m_online)
  650. {
  651. throw new NotConnectedException(TouchSocketStatus.NotConnected.GetDescription());
  652. }
  653. if (HandleSendingData(buffer, offset, length))
  654. {
  655. if (UseSsl)
  656. {
  657. m_workStream.Write(buffer, offset, length);
  658. }
  659. else
  660. {
  661. if (m_useDelaySender && length < TouchSocketUtility.BigDataBoundary)
  662. {
  663. m_delaySender.Send(new QueueDataBytes(buffer, offset, length));
  664. }
  665. else
  666. {
  667. m_mainSocket.AbsoluteSend(buffer, offset, length);
  668. }
  669. }
  670. LastSendTime = DateTime.Now;
  671. }
  672. }
  673. /// <summary>
  674. /// <inheritdoc/>
  675. /// </summary>
  676. /// <param name="buffer"><inheritdoc/></param>
  677. /// <param name="offset"><inheritdoc/></param>
  678. /// <param name="length"><inheritdoc/></param>
  679. /// <exception cref="NotConnectedException"><inheritdoc/></exception>
  680. /// <exception cref="OverlengthException"><inheritdoc/></exception>
  681. /// <exception cref="Exception"><inheritdoc/></exception>
  682. public Task DefaultSendAsync(byte[] buffer, int offset, int length)
  683. {
  684. return EasyTask.Run(() =>
  685. {
  686. DefaultSend(buffer, offset, length);
  687. });
  688. }
  689. #region 同步发送
  690. /// <summary>
  691. /// <inheritdoc/>
  692. /// </summary>
  693. /// <param name="requestInfo"></param>
  694. /// <exception cref="NotConnectedException"></exception>
  695. /// <exception cref="OverlengthException"></exception>
  696. /// <exception cref="Exception"></exception>
  697. public virtual void Send(IRequestInfo requestInfo)
  698. {
  699. if (DisposedValue)
  700. {
  701. return;
  702. }
  703. if (m_adapter == null)
  704. {
  705. throw new ArgumentNullException(nameof(DataHandlingAdapter), TouchSocketStatus.NullDataAdapter.GetDescription());
  706. }
  707. if (!m_adapter.CanSendRequestInfo)
  708. {
  709. throw new NotSupportedException($"当前适配器不支持对象发送。");
  710. }
  711. m_adapter.SendInput(requestInfo);
  712. }
  713. /// <summary>
  714. /// 发送字节流
  715. /// </summary>
  716. /// <param name="buffer"></param>
  717. /// <param name="offset"></param>
  718. /// <param name="length"></param>
  719. /// <exception cref="NotConnectedException"></exception>
  720. /// <exception cref="OverlengthException"></exception>
  721. /// <exception cref="Exception"></exception>
  722. public virtual void Send(byte[] buffer, int offset, int length)
  723. {
  724. if (DisposedValue)
  725. {
  726. return;
  727. }
  728. if (m_adapter == null)
  729. {
  730. throw new ArgumentNullException(nameof(DataHandlingAdapter), TouchSocketStatus.NullDataAdapter.GetDescription());
  731. }
  732. m_adapter.SendInput(buffer, offset, length);
  733. }
  734. /// <summary>
  735. /// <inheritdoc/>
  736. /// </summary>
  737. /// <param name="transferBytes"></param>
  738. public virtual void Send(IList<ArraySegment<byte>> transferBytes)
  739. {
  740. if (DisposedValue)
  741. {
  742. return;
  743. }
  744. if (m_adapter == null)
  745. {
  746. throw new ArgumentNullException(nameof(DataHandlingAdapter), TouchSocketStatus.NullDataAdapter.GetDescription());
  747. }
  748. if (m_adapter.CanSplicingSend)
  749. {
  750. m_adapter.SendInput(transferBytes);
  751. }
  752. else
  753. {
  754. ByteBlock byteBlock = new ByteBlock(BufferLength);
  755. try
  756. {
  757. foreach (var item in transferBytes)
  758. {
  759. byteBlock.Write(item.Array, item.Offset, item.Count);
  760. }
  761. m_adapter.SendInput(byteBlock.Buffer, 0, byteBlock.Len);
  762. }
  763. finally
  764. {
  765. byteBlock.Dispose();
  766. }
  767. }
  768. }
  769. #endregion 同步发送
  770. #region 异步发送
  771. /// <summary>
  772. /// IOCP发送
  773. /// </summary>
  774. /// <param name="buffer"></param>
  775. /// <param name="offset"></param>
  776. /// <param name="length"></param>
  777. /// <exception cref="NotConnectedException"></exception>
  778. /// <exception cref="OverlengthException"></exception>
  779. /// <exception cref="Exception"></exception>
  780. public virtual Task SendAsync(byte[] buffer, int offset, int length)
  781. {
  782. return EasyTask.Run(() =>
  783. {
  784. Send(buffer, offset, length);
  785. });
  786. }
  787. /// <summary>
  788. /// <inheritdoc/>
  789. /// </summary>
  790. /// <param name="requestInfo"></param>
  791. /// <exception cref="NotConnectedException"></exception>
  792. /// <exception cref="OverlengthException"></exception>
  793. /// <exception cref="Exception"></exception>
  794. public virtual Task SendAsync(IRequestInfo requestInfo)
  795. {
  796. return EasyTask.Run(() =>
  797. {
  798. Send(requestInfo);
  799. });
  800. }
  801. /// <summary>
  802. /// <inheritdoc/>
  803. /// </summary>
  804. /// <param name="transferBytes"></param>
  805. public virtual Task SendAsync(IList<ArraySegment<byte>> transferBytes)
  806. {
  807. return EasyTask.Run(() =>
  808. {
  809. Send(transferBytes);
  810. });
  811. }
  812. #endregion 异步发送
  813. #region ID发送
  814. /// <summary>
  815. /// 发送字节流
  816. /// </summary>
  817. /// <param name="id">用于检索TcpSocketClient</param>
  818. /// <param name="buffer"></param>
  819. /// <param name="offset"></param>
  820. /// <param name="length"></param>
  821. /// <exception cref="KeyNotFoundException"></exception>
  822. /// <exception cref="NotConnectedException"></exception>
  823. /// <exception cref="OverlengthException"></exception>
  824. /// <exception cref="Exception"></exception>
  825. public void Send(string id, byte[] buffer, int offset, int length)
  826. {
  827. m_service.Send(id, buffer, offset, length);
  828. }
  829. /// <summary>
  830. /// <inheritdoc/>
  831. /// </summary>
  832. /// <param name="id"></param>
  833. /// <param name="requestInfo"></param>
  834. public void Send(string id, IRequestInfo requestInfo)
  835. {
  836. m_service.Send(id, requestInfo);
  837. }
  838. /// <summary>
  839. /// 发送字节流
  840. /// </summary>
  841. /// <param name="id">用于检索TcpSocketClient</param>
  842. /// <param name="buffer"></param>
  843. /// <param name="offset"></param>
  844. /// <param name="length"></param>
  845. /// <exception cref="KeyNotFoundException"></exception>
  846. /// <exception cref="NotConnectedException"></exception>
  847. /// <exception cref="OverlengthException"></exception>
  848. /// <exception cref="Exception"></exception>
  849. public Task SendAsync(string id, byte[] buffer, int offset, int length)
  850. {
  851. return m_service.SendAsync(id, buffer, offset, length);
  852. }
  853. /// <summary>
  854. /// <inheritdoc/>
  855. /// </summary>
  856. /// <param name="id"></param>
  857. /// <param name="requestInfo"></param>
  858. public Task SendAsync(string id, IRequestInfo requestInfo)
  859. {
  860. return m_service.SendAsync(id, requestInfo);
  861. }
  862. #endregion ID发送
  863. #endregion 发送
  864. }
  865. }