Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 

81 рядки
2.1 KiB

  1. using System;
  2. using System.Net.Sockets;
  3. using System.Threading.Tasks;
  4. using MQTTnet.Core.Channel;
  5. using MQTTnet.Core.Client;
  6. using MQTTnet.Core.Exceptions;
  7. namespace MQTTnet
  8. {
  9. public class MqttTcpChannel : IMqttCommunicationChannel, IDisposable
  10. {
  11. private readonly Socket _socket;
  12. public MqttTcpChannel()
  13. {
  14. _socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
  15. }
  16. public MqttTcpChannel(Socket socket)
  17. {
  18. _socket = socket ?? throw new ArgumentNullException(nameof(socket));
  19. }
  20. public Task ConnectAsync(MqttClientOptions options)
  21. {
  22. try
  23. {
  24. return _socket.ConnectAsync(options.Server, options.Port);
  25. }
  26. catch (SocketException exception)
  27. {
  28. throw new MqttCommunicationException(exception);
  29. }
  30. }
  31. public Task DisconnectAsync()
  32. {
  33. try
  34. {
  35. _socket.Dispose();
  36. return Task.FromResult(0);
  37. }
  38. catch (SocketException exception)
  39. {
  40. throw new MqttCommunicationException(exception);
  41. }
  42. }
  43. public Task WriteAsync(byte[] buffer)
  44. {
  45. if (buffer == null) throw new ArgumentNullException(nameof(buffer));
  46. try
  47. {
  48. return _socket.SendAsync(new ArraySegment<byte>(buffer), SocketFlags.None);
  49. }
  50. catch (SocketException exception)
  51. {
  52. throw new MqttCommunicationException(exception);
  53. }
  54. }
  55. public Task ReadAsync(byte[] buffer)
  56. {
  57. try
  58. {
  59. var buffer2 = new ArraySegment<byte>(buffer);
  60. return _socket.ReceiveAsync(buffer2, SocketFlags.None);
  61. }
  62. catch (SocketException exception)
  63. {
  64. throw new MqttCommunicationException(exception);
  65. }
  66. }
  67. public void Dispose()
  68. {
  69. _socket?.Dispose();
  70. }
  71. }
  72. }