25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

85 lines
2.5 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 async Task ConnectAsync(MqttClientOptions options)
  21. {
  22. try
  23. {
  24. await Task.Factory.FromAsync(_socket.BeginConnect, _socket.EndConnect, options.Server, options.Port, null);
  25. }
  26. catch (SocketException exception)
  27. {
  28. throw new MqttCommunicationException(exception);
  29. }
  30. }
  31. public async Task DisconnectAsync()
  32. {
  33. try
  34. {
  35. await Task.Factory.FromAsync(_socket.BeginDisconnect, _socket.EndDisconnect, true, null);
  36. }
  37. catch (SocketException exception)
  38. {
  39. throw new MqttCommunicationException(exception);
  40. }
  41. }
  42. public async Task WriteAsync(byte[] buffer)
  43. {
  44. if (buffer == null) throw new ArgumentNullException(nameof(buffer));
  45. try
  46. {
  47. await Task.Factory.FromAsync(
  48. // ReSharper disable once AssignNullToNotNullAttribute
  49. _socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, null, null),
  50. _socket.EndSend);
  51. }
  52. catch (SocketException exception)
  53. {
  54. throw new MqttCommunicationException(exception);
  55. }
  56. }
  57. public async Task ReadAsync(byte[] buffer)
  58. {
  59. try
  60. {
  61. await Task.Factory.FromAsync(
  62. // ReSharper disable once AssignNullToNotNullAttribute
  63. _socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, null, null),
  64. _socket.EndReceive);
  65. }
  66. catch (SocketException exception)
  67. {
  68. throw new MqttCommunicationException(exception);
  69. }
  70. }
  71. public void Dispose()
  72. {
  73. _socket?.Dispose();
  74. }
  75. }
  76. }