TcpSocketClient.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Net.Security;
  5. using System.Net.Sockets;
  6. using System.Security.Cryptography.X509Certificates;
  7. using System.Threading;
  8. using Aitex.Core.RT.Log;
  9. using MECF.Framework.Common.Communications.Tcp.Buffer;
  10. using MECF.Framework.Common.Communications.Tcp.Socket.Client.APM.EventArgs;
  11. namespace MECF.Framework.Common.Communications.Tcp.Socket.Client.APM
  12. {
  13. public class TcpSocketClient : IDisposable
  14. {
  15. #region Fields
  16. // private static readonly ILogger _log = LoggerManager.GetLogger(Assembly.GetExecutingAssembly(), "Tcp");//. .Get<TcpSocketClient>();
  17. private TcpClient _tcpClient;
  18. private readonly TcpSocketClientConfiguration _configuration;
  19. private readonly IPEndPoint _remoteEndPoint;
  20. private readonly IPEndPoint _localEndPoint;
  21. private Stream _stream;
  22. private ArraySegment<byte> _receiveBuffer = default(ArraySegment<byte>);
  23. private int _receiveBufferOffset = 0;
  24. private int _state;
  25. private const int _none = 0;
  26. private const int _connecting = 1;
  27. private const int _connected = 2;
  28. private const int _closed = 5;
  29. #endregion
  30. #region Constructors
  31. public TcpSocketClient(IPAddress remoteAddress, int remotePort, IPAddress localAddress, int localPort, TcpSocketClientConfiguration configuration = null)
  32. : this(new IPEndPoint(remoteAddress, remotePort), new IPEndPoint(localAddress, localPort), configuration)
  33. {
  34. }
  35. public TcpSocketClient(IPAddress remoteAddress, int remotePort, IPEndPoint localEP = null, TcpSocketClientConfiguration configuration = null)
  36. : this(new IPEndPoint(remoteAddress, remotePort), localEP, configuration)
  37. {
  38. }
  39. public TcpSocketClient(IPEndPoint remoteEP, TcpSocketClientConfiguration configuration = null)
  40. : this(remoteEP, null, configuration)
  41. {
  42. }
  43. public TcpSocketClient(IPEndPoint remoteEP, IPEndPoint localEP, TcpSocketClientConfiguration configuration = null)
  44. {
  45. if (remoteEP == null)
  46. throw new ArgumentNullException("remoteEP");
  47. _remoteEndPoint = remoteEP;
  48. _localEndPoint = localEP;
  49. _configuration = configuration ?? new TcpSocketClientConfiguration();
  50. if (_configuration.BufferManager == null)
  51. throw new InvalidProgramException("The buffer manager in configuration cannot be null.");
  52. if (_configuration.FrameBuilder == null)
  53. throw new InvalidProgramException("The frame handler in configuration cannot be null.");
  54. }
  55. #endregion
  56. #region Properties
  57. public TimeSpan ConnectTimeout { get { return _configuration.ConnectTimeout; } }
  58. private bool Connected { get { return _tcpClient != null && _tcpClient.Client.Connected; } }
  59. public IPEndPoint RemoteEndPoint { get { return Connected ? (IPEndPoint)_tcpClient.Client.RemoteEndPoint : _remoteEndPoint; } }
  60. public IPEndPoint LocalEndPoint { get { return Connected ? (IPEndPoint)_tcpClient.Client.LocalEndPoint : _localEndPoint; } }
  61. public TcpSocketConnectionState State
  62. {
  63. get
  64. {
  65. switch (_state)
  66. {
  67. case _none:
  68. return TcpSocketConnectionState.None;
  69. case _connecting:
  70. return TcpSocketConnectionState.Connecting;
  71. case _connected:
  72. return TcpSocketConnectionState.Connected;
  73. case _closed:
  74. return TcpSocketConnectionState.Closed;
  75. default:
  76. return TcpSocketConnectionState.Closed;
  77. }
  78. }
  79. }
  80. public override string ToString()
  81. {
  82. return string.Format("RemoteEndPoint[{0}], LocalEndPoint[{1}]",
  83. this.RemoteEndPoint, this.LocalEndPoint);
  84. }
  85. /// <summary>
  86. /// Checks the connection state
  87. /// </summary>
  88. /// <returns>True on connected. False on disconnected.</returns>
  89. public bool IsConnected()
  90. {
  91. if (Connected)
  92. {
  93. if ((_tcpClient.Client.Poll(0, SelectMode.SelectWrite)) && (!_tcpClient.Client.Poll(0, SelectMode.SelectError)))
  94. {
  95. byte[] buffer = new byte[1];
  96. if (_tcpClient.Client.Receive(buffer, SocketFlags.Peek) == 0)
  97. {
  98. return false;
  99. }
  100. else
  101. {
  102. return true;
  103. }
  104. }
  105. else
  106. {
  107. return false;
  108. }
  109. }
  110. else
  111. {
  112. return false;
  113. }
  114. }
  115. #endregion
  116. #region Connect
  117. public void Connect()
  118. {
  119. int origin = Interlocked.Exchange(ref _state, _connecting);
  120. if (!(origin == _none || origin == _closed))
  121. {
  122. Close(false);
  123. throw new InvalidOperationException("This tcp socket client is in invalid state when connecting.");
  124. }
  125. Clean();
  126. _tcpClient = _localEndPoint != null ?
  127. new TcpClient(_localEndPoint) :
  128. new TcpClient(_remoteEndPoint.Address.AddressFamily);
  129. SetSocketOptions();
  130. var ar = _tcpClient.BeginConnect(_remoteEndPoint.Address, _remoteEndPoint.Port, null, _tcpClient);
  131. if (!ar.AsyncWaitHandle.WaitOne(ConnectTimeout))
  132. {
  133. Close(false);
  134. throw new TimeoutException(string.Format(
  135. "Connect to [{0}] timeout [{1}].", _remoteEndPoint, ConnectTimeout));
  136. }
  137. try
  138. {
  139. _tcpClient.EndConnect(ar);
  140. }
  141. catch (Exception ex)
  142. {
  143. Close(false);
  144. throw ex;
  145. }
  146. if (Interlocked.CompareExchange(ref _state, _connected, _connecting) != _connecting)
  147. {
  148. Close(false);
  149. throw new InvalidOperationException("This tcp socket client is in invalid state when connected.");
  150. }
  151. if (_receiveBuffer == default(ArraySegment<byte>))
  152. _receiveBuffer = _configuration.BufferManager.BorrowBuffer();
  153. _receiveBufferOffset = 0;
  154. HandleTcpServerConnected();
  155. }
  156. public void Close()
  157. {
  158. Close(true);
  159. }
  160. private void Close(bool shallNotifyUserSide)
  161. {
  162. if (Interlocked.Exchange(ref _state, _closed) == _closed)
  163. {
  164. return;
  165. }
  166. Clean();
  167. if (shallNotifyUserSide)
  168. {
  169. try
  170. {
  171. RaiseServerDisconnected();
  172. }
  173. catch (Exception ex)
  174. {
  175. HandleUserSideError(ex);
  176. }
  177. }
  178. }
  179. private void Clean()
  180. {
  181. try
  182. {
  183. try
  184. {
  185. if (_stream != null)
  186. {
  187. _stream.Dispose();
  188. }
  189. }
  190. catch { }
  191. try
  192. {
  193. if (_tcpClient != null)
  194. {
  195. _tcpClient.Close();
  196. }
  197. }
  198. catch { }
  199. }
  200. catch { }
  201. finally
  202. {
  203. _stream = null;
  204. _tcpClient = null;
  205. }
  206. if (_receiveBuffer != default(ArraySegment<byte>))
  207. _configuration.BufferManager.ReturnBuffer(_receiveBuffer);
  208. _receiveBuffer = default(ArraySegment<byte>);
  209. _receiveBufferOffset = 0;
  210. }
  211. #endregion
  212. #region Receive
  213. private void HandleTcpServerConnected()
  214. {
  215. try
  216. {
  217. _stream = NegotiateStream(_tcpClient.GetStream());
  218. bool isErrorOccurredInUserSide = false;
  219. try
  220. {
  221. RaiseServerConnected();
  222. }
  223. catch (Exception ex)
  224. {
  225. isErrorOccurredInUserSide = true;
  226. HandleUserSideError(ex);
  227. }
  228. if (!isErrorOccurredInUserSide)
  229. {
  230. ContinueReadBuffer();
  231. }
  232. else
  233. {
  234. Close();
  235. }
  236. }
  237. catch (Exception ex)
  238. {
  239. LOG.Error(ex.Message, ex);
  240. Close();
  241. }
  242. }
  243. private void SetSocketOptions()
  244. {
  245. _tcpClient.ReceiveBufferSize = _configuration.ReceiveBufferSize;
  246. _tcpClient.SendBufferSize = _configuration.SendBufferSize;
  247. _tcpClient.ReceiveTimeout = (int)_configuration.ReceiveTimeout.TotalMilliseconds;
  248. _tcpClient.SendTimeout = (int)_configuration.SendTimeout.TotalMilliseconds;
  249. _tcpClient.NoDelay = _configuration.NoDelay;
  250. _tcpClient.LingerState = _configuration.LingerState;
  251. if (_configuration.KeepAlive)
  252. {
  253. _tcpClient.Client.SetSocketOption(
  254. SocketOptionLevel.Socket,
  255. SocketOptionName.KeepAlive,
  256. (int)_configuration.KeepAliveInterval.TotalMilliseconds);
  257. }
  258. _tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, _configuration.ReuseAddress);
  259. }
  260. private Stream NegotiateStream(Stream stream)
  261. {
  262. if (!_configuration.SslEnabled)
  263. return stream;
  264. var validateRemoteCertificate = new RemoteCertificateValidationCallback(
  265. (object sender,
  266. X509Certificate certificate,
  267. X509Chain chain,
  268. SslPolicyErrors sslPolicyErrors)
  269. =>
  270. {
  271. if (sslPolicyErrors == SslPolicyErrors.None)
  272. return true;
  273. if (_configuration.SslPolicyErrorsBypassed)
  274. return true;
  275. else
  276. LOG.Write(string.Format("Error occurred when validating remote certificate: [{0}], [{1}].",
  277. this.RemoteEndPoint, sslPolicyErrors));
  278. return false;
  279. });
  280. var sslStream = new SslStream(
  281. stream,
  282. false,
  283. validateRemoteCertificate,
  284. null,
  285. _configuration.SslEncryptionPolicy);
  286. IAsyncResult ar = null;
  287. if (_configuration.SslClientCertificates == null || _configuration.SslClientCertificates.Count == 0)
  288. {
  289. ar = sslStream.BeginAuthenticateAsClient( // No client certificates are used in the authentication. The certificate revocation list is not checked during authentication.
  290. _configuration.SslTargetHost, // The name of the server that will share this SslStream. The value specified for targetHost must match the name on the server's certificate.
  291. null, _tcpClient);
  292. }
  293. else
  294. {
  295. ar = sslStream.BeginAuthenticateAsClient(
  296. _configuration.SslTargetHost, // The name of the server that will share this SslStream. The value specified for targetHost must match the name on the server's certificate.
  297. _configuration.SslClientCertificates, // The X509CertificateCollection that contains client certificates.
  298. _configuration.SslEnabledProtocols, // The SslProtocols value that represents the protocol used for authentication.
  299. _configuration.SslCheckCertificateRevocation, // A Boolean value that specifies whether the certificate revocation list is checked during authentication.
  300. null, _tcpClient);
  301. }
  302. if (!ar.AsyncWaitHandle.WaitOne(ConnectTimeout))
  303. {
  304. Close(false);
  305. throw new TimeoutException(string.Format(
  306. "Negotiate SSL/TSL with remote [{0}] timeout [{1}].", this.RemoteEndPoint, ConnectTimeout));
  307. }
  308. sslStream.EndAuthenticateAsClient(ar);
  309. // When authentication succeeds, you must check the IsEncrypted and IsSigned properties
  310. // to determine what security services are used by the SslStream.
  311. // Check the IsMutuallyAuthenticated property to determine whether mutual authentication occurred.
  312. LOG.Write(string.Format(
  313. "Ssl Stream: SslProtocol[{0}], IsServer[{1}], IsAuthenticated[{2}], IsEncrypted[{3}], IsSigned[{4}], IsMutuallyAuthenticated[{5}], "
  314. + "HashAlgorithm[{6}], HashStrength[{7}], KeyExchangeAlgorithm[{8}], KeyExchangeStrength[{9}], CipherAlgorithm[{10}], CipherStrength[{11}].",
  315. sslStream.SslProtocol,
  316. sslStream.IsServer,
  317. sslStream.IsAuthenticated,
  318. sslStream.IsEncrypted,
  319. sslStream.IsSigned,
  320. sslStream.IsMutuallyAuthenticated,
  321. sslStream.HashAlgorithm,
  322. sslStream.HashStrength,
  323. sslStream.KeyExchangeAlgorithm,
  324. sslStream.KeyExchangeStrength,
  325. sslStream.CipherAlgorithm,
  326. sslStream.CipherStrength));
  327. return sslStream;
  328. }
  329. private void ContinueReadBuffer()
  330. {
  331. try
  332. {
  333. _stream.BeginRead(
  334. _receiveBuffer.Array,
  335. _receiveBuffer.Offset + _receiveBufferOffset,
  336. _receiveBuffer.Count - _receiveBufferOffset,
  337. HandleDataReceived,
  338. _stream);
  339. }
  340. catch (Exception ex)
  341. {
  342. if (!CloseIfShould(ex))
  343. throw;
  344. }
  345. }
  346. private void HandleDataReceived(IAsyncResult ar)
  347. {
  348. if (this.State != TcpSocketConnectionState.Connected)
  349. return;
  350. try
  351. {
  352. // when callback to here the stream may have been closed
  353. if (_stream == null)
  354. return;
  355. int numberOfReadBytes = 0;
  356. try
  357. {
  358. // The EndRead method blocks until data is available. The EndRead method reads
  359. // as much data as is available up to the number of bytes specified in the size
  360. // parameter of the BeginRead method. If the remote host shuts down the Socket
  361. // connection and all available data has been received, the EndRead method
  362. // completes immediately and returns zero bytes.
  363. numberOfReadBytes = _stream.EndRead(ar);
  364. }
  365. catch (Exception)
  366. {
  367. // unable to read data from transport connection,
  368. // the existing connection was forcibly closed by remote host
  369. numberOfReadBytes = 0;
  370. }
  371. if (numberOfReadBytes == 0)
  372. {
  373. // connection has been closed
  374. Close();
  375. return;
  376. }
  377. ReceiveBuffer(numberOfReadBytes);
  378. ContinueReadBuffer();
  379. }
  380. catch (Exception ex)
  381. {
  382. if (!CloseIfShould(ex))
  383. throw;
  384. }
  385. }
  386. private void ReceiveBuffer(int receiveCount)
  387. {
  388. // TCP guarantees delivery of all packets in the correct order.
  389. // But there is no guarantee that one write operation on the sender-side will result in
  390. // one read event on the receiving side. One call of write(message) by the sender
  391. // can result in multiple messageReceived(session, message) events on the receiver;
  392. // and multiple calls of write(message) can lead to a single messageReceived event.
  393. // In a stream-based transport such as TCP/IP, received data is stored into a socket receive buffer.
  394. // Unfortunately, the buffer of a stream-based transport is not a queue of packets but a queue of bytes.
  395. // It means, even if you sent two messages as two independent packets,
  396. // an operating system will not treat them as two messages but as just a bunch of bytes.
  397. // Therefore, there is no guarantee that what you read is exactly what your remote peer wrote.
  398. // There are three common techniques for splitting the stream of bytes into messages:
  399. // 1. use fixed length messages
  400. // 2. use a fixed length header that indicates the length of the body
  401. // 3. using a delimiter; for example many text-based protocols append
  402. // a newline (or CR LF pair) after every message.
  403. int frameLength;
  404. byte[] payload;
  405. int payloadOffset;
  406. int payloadCount;
  407. int consumedLength = 0;
  408. SegmentBufferDeflector.ReplaceBuffer(_configuration.BufferManager, ref _receiveBuffer, ref _receiveBufferOffset, receiveCount);
  409. while (true)
  410. {
  411. frameLength = 0;
  412. payload = null;
  413. payloadOffset = 0;
  414. payloadCount = 0;
  415. if (_configuration.FrameBuilder.Decoder.TryDecodeFrame(
  416. _receiveBuffer.Array,
  417. _receiveBuffer.Offset + consumedLength,
  418. _receiveBufferOffset - consumedLength,
  419. out frameLength, out payload, out payloadOffset, out payloadCount))
  420. {
  421. try
  422. {
  423. RaiseServerDataReceived(payload, payloadOffset, payloadCount);
  424. }
  425. catch (Exception ex)
  426. {
  427. HandleUserSideError(ex);
  428. }
  429. finally
  430. {
  431. consumedLength += frameLength;
  432. }
  433. }
  434. else
  435. {
  436. break;
  437. }
  438. }
  439. try
  440. {
  441. SegmentBufferDeflector.ShiftBuffer(_configuration.BufferManager, consumedLength, ref _receiveBuffer, ref _receiveBufferOffset);
  442. }
  443. catch (ArgumentOutOfRangeException) { }
  444. }
  445. #endregion
  446. #region Exception Handler
  447. private bool IsSocketTimeOut(Exception ex)
  448. {
  449. return ex is IOException
  450. && ex.InnerException != null
  451. && ex.InnerException is SocketException
  452. && (ex.InnerException as SocketException).SocketErrorCode == SocketError.TimedOut;
  453. }
  454. private bool CloseIfShould(Exception ex)
  455. {
  456. if (ex is ObjectDisposedException
  457. || ex is InvalidOperationException
  458. || ex is SocketException
  459. || ex is IOException
  460. || ex is NullReferenceException
  461. )
  462. {
  463. LOG.Error(ex.Message, ex);
  464. Close();
  465. return true;
  466. }
  467. return false;
  468. }
  469. private void HandleUserSideError(Exception ex)
  470. {
  471. LOG.Error(string.Format("Client [{0}] error occurred in user side [{1}].", this, ex.Message), ex);
  472. }
  473. #endregion
  474. #region Send
  475. public void Send(byte[] data)
  476. {
  477. if (data == null)
  478. throw new ArgumentNullException("data");
  479. Send(data, 0, data.Length);
  480. }
  481. public void Send(byte[] data, int offset, int count)
  482. {
  483. BufferValidator.ValidateBuffer(data, offset, count, "data");
  484. if (this.State != TcpSocketConnectionState.Connected)
  485. {
  486. throw new InvalidProgramException("This client has not connected to server.");
  487. }
  488. try
  489. {
  490. byte[] frameBuffer;
  491. int frameBufferOffset;
  492. int frameBufferLength;
  493. _configuration.FrameBuilder.Encoder.EncodeFrame(data, offset, count, out frameBuffer, out frameBufferOffset, out frameBufferLength);
  494. _stream.Write(frameBuffer, frameBufferOffset, frameBufferLength);
  495. }
  496. catch (Exception ex)
  497. {
  498. if (IsSocketTimeOut(ex))
  499. {
  500. LOG.Error(ex.Message, ex);
  501. }
  502. else
  503. {
  504. if (!CloseIfShould(ex))
  505. throw;
  506. }
  507. }
  508. }
  509. public void BeginSend(byte[] data)
  510. {
  511. if (data == null)
  512. throw new ArgumentNullException("data");
  513. BeginSend(data, 0, data.Length);
  514. }
  515. public void BeginSend(byte[] data, int offset, int count)
  516. {
  517. BufferValidator.ValidateBuffer(data, offset, count, "data");
  518. if (this.State != TcpSocketConnectionState.Connected)
  519. {
  520. throw new InvalidProgramException("This client has not connected to server.");
  521. }
  522. try
  523. {
  524. byte[] frameBuffer;
  525. int frameBufferOffset;
  526. int frameBufferLength;
  527. _configuration.FrameBuilder.Encoder.EncodeFrame(data, offset, count, out frameBuffer, out frameBufferOffset, out frameBufferLength);
  528. _stream.BeginWrite(frameBuffer, frameBufferOffset, frameBufferLength, HandleDataWritten, _stream);
  529. }
  530. catch (Exception ex)
  531. {
  532. if (IsSocketTimeOut(ex))
  533. {
  534. LOG.Error(ex.Message, ex);
  535. }
  536. else
  537. {
  538. if (!CloseIfShould(ex))
  539. throw;
  540. }
  541. }
  542. }
  543. private void HandleDataWritten(IAsyncResult ar)
  544. {
  545. try
  546. {
  547. _stream.EndWrite(ar);
  548. }
  549. catch (Exception ex)
  550. {
  551. if (!CloseIfShould(ex))
  552. throw;
  553. }
  554. }
  555. public IAsyncResult BeginSend(byte[] data, AsyncCallback callback, object state)
  556. {
  557. if (data == null)
  558. throw new ArgumentNullException("data");
  559. return BeginSend(data, 0, data.Length, callback, state);
  560. }
  561. public IAsyncResult BeginSend(byte[] data, int offset, int count, AsyncCallback callback, object state)
  562. {
  563. BufferValidator.ValidateBuffer(data, offset, count, "data");
  564. if (this.State != TcpSocketConnectionState.Connected)
  565. {
  566. throw new InvalidProgramException("This client has not connected to server.");
  567. }
  568. try
  569. {
  570. byte[] frameBuffer;
  571. int frameBufferOffset;
  572. int frameBufferLength;
  573. _configuration.FrameBuilder.Encoder.EncodeFrame(data, offset, count, out frameBuffer, out frameBufferOffset, out frameBufferLength);
  574. return _stream.BeginWrite(frameBuffer, frameBufferOffset, frameBufferLength, callback, state);
  575. }
  576. catch (Exception ex)
  577. {
  578. if (IsSocketTimeOut(ex))
  579. {
  580. LOG.Error(ex.Message, ex);
  581. }
  582. else
  583. {
  584. if (!CloseIfShould(ex))
  585. throw;
  586. }
  587. throw;
  588. }
  589. }
  590. public void EndSend(IAsyncResult asyncResult)
  591. {
  592. HandleDataWritten(asyncResult);
  593. }
  594. #endregion
  595. #region Events
  596. public event EventHandler<TcpServerConnectedEventArgs> ServerConnected;
  597. public event EventHandler<TcpServerDisconnectedEventArgs> ServerDisconnected;
  598. public event EventHandler<TcpServerDataReceivedEventArgs> ServerDataReceived;
  599. private void RaiseServerConnected()
  600. {
  601. if (ServerConnected != null)
  602. {
  603. ServerConnected(this, new TcpServerConnectedEventArgs(this.RemoteEndPoint, this.LocalEndPoint));
  604. }
  605. }
  606. private void RaiseServerDisconnected()
  607. {
  608. if (ServerDisconnected != null)
  609. {
  610. ServerDisconnected(this, new TcpServerDisconnectedEventArgs(_remoteEndPoint, _localEndPoint));
  611. }
  612. }
  613. private void RaiseServerDataReceived(byte[] data, int dataOffset, int dataLength)
  614. {
  615. if (ServerDataReceived != null)
  616. {
  617. ServerDataReceived(this, new TcpServerDataReceivedEventArgs(this, data, dataOffset, dataLength));
  618. }
  619. }
  620. #endregion
  621. #region IDisposable Members
  622. public void Dispose()
  623. {
  624. Dispose(true);
  625. GC.SuppressFinalize(this);
  626. }
  627. protected virtual void Dispose(bool disposing)
  628. {
  629. if (disposing)
  630. {
  631. try
  632. {
  633. Close();
  634. }
  635. catch (Exception ex)
  636. {
  637. LOG.Error(ex.Message, ex);
  638. }
  639. }
  640. }
  641. #endregion
  642. }
  643. }