TcpClientAdapter.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Diagnostics;
  3. using System.Net.Sockets;
  4. using System.Threading;
  5. using NModbus.Unme.Common;
  6. namespace NModbus.IO
  7. {
  8. /// <summary>
  9. /// Concrete Implementor - http://en.wikipedia.org/wiki/Bridge_Pattern
  10. /// </summary>
  11. public class TcpClientAdapter : IStreamResource
  12. {
  13. private TcpClient _tcpClient;
  14. public TcpClientAdapter(TcpClient tcpClient)
  15. {
  16. Debug.Assert(tcpClient != null, "Argument tcpClient cannot be null.");
  17. _tcpClient = tcpClient;
  18. }
  19. public int InfiniteTimeout => Timeout.Infinite;
  20. public int ReadTimeout
  21. {
  22. get => _tcpClient.GetStream().ReadTimeout;
  23. set => _tcpClient.GetStream().ReadTimeout = value;
  24. }
  25. public int WriteTimeout
  26. {
  27. get => _tcpClient.GetStream().WriteTimeout;
  28. set => _tcpClient.GetStream().WriteTimeout = value;
  29. }
  30. public void Write(byte[] buffer, int offset, int size)
  31. {
  32. _tcpClient.GetStream().Write(buffer, offset, size);
  33. }
  34. public int Read(byte[] buffer, int offset, int size)
  35. {
  36. return _tcpClient.GetStream().Read(buffer, offset, size);
  37. }
  38. public void DiscardInBuffer()
  39. {
  40. _tcpClient.GetStream().Flush();
  41. }
  42. public void Dispose()
  43. {
  44. Dispose(true);
  45. GC.SuppressFinalize(this);
  46. }
  47. protected virtual void Dispose(bool disposing)
  48. {
  49. if (disposing)
  50. {
  51. DisposableUtility.Dispose(ref _tcpClient);
  52. }
  53. }
  54. }
  55. }