SocketAdapter.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. /// This implementation is for sockets that Convert Rs485 to Ethernet.
  11. /// </summary>
  12. public class SocketAdapter : IStreamResource
  13. {
  14. private Socket _socketClient;
  15. public SocketAdapter(Socket socketClient)
  16. {
  17. Debug.Assert(socketClient != null, "Argument socketClient van not be null");
  18. _socketClient = socketClient;
  19. }
  20. public int InfiniteTimeout => Timeout.Infinite;
  21. public int ReadTimeout
  22. {
  23. get => _socketClient.SendTimeout;
  24. set => _socketClient.SendTimeout = value;
  25. }
  26. public int WriteTimeout
  27. {
  28. get => _socketClient.ReceiveTimeout;
  29. set => _socketClient.ReceiveTimeout = value;
  30. }
  31. public void DiscardInBuffer()
  32. {
  33. // socket does not hold buffers.
  34. return;
  35. }
  36. public int Read(byte[] buffer, int offset, int size)
  37. {
  38. return _socketClient.Receive(buffer,offset,size,0);
  39. }
  40. public void Write(byte[] buffer, int offset, int size)
  41. {
  42. _socketClient.Send(buffer,offset,size,0);
  43. }
  44. public void Dispose()
  45. {
  46. Dispose(true);
  47. GC.SuppressFinalize(this);
  48. }
  49. protected virtual void Dispose(bool disposing)
  50. {
  51. if (disposing)
  52. {
  53. DisposableUtility.Dispose(ref _socketClient);
  54. }
  55. }
  56. }
  57. }