選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 

271 行
9.9 KiB

  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Security.Authentication;
  5. using MQTTnet.Client;
  6. using MQTTnet.Formatter;
  7. using MQTTnet.Samples.Helpers;
  8. namespace MQTTnet.Samples.Client;
  9. public static class Client_Connection_Samples
  10. {
  11. public static async Task Connect_Client()
  12. {
  13. /*
  14. * This sample creates a simple MQTT client and connects to a public broker.
  15. *
  16. * Always dispose the client when it is no longer used.
  17. * The default version of MQTT is 3.1.1.
  18. */
  19. var mqttFactory = new MqttFactory();
  20. using (var mqttClient = mqttFactory.CreateMqttClient())
  21. {
  22. // Use builder classes where possible in this project.
  23. var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer("broker.hivemq.com").Build();
  24. // This will throw an exception if the server is not available.
  25. // The result from this message returns additional data which was sent
  26. // from the server. Please refer to the MQTT protocol specification for details.
  27. var response = await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
  28. Console.WriteLine("The MQTT client is connected.");
  29. response.DumpToConsole();
  30. // Send a clean disconnect to the server by calling _DisconnectAsync_. Without this the TCP connection
  31. // gets dropped and the server will handle this as a non clean disconnect (see MQTT spec for details).
  32. var mqttClientDisconnectOptions = mqttFactory.CreateClientDisconnectOptionsBuilder().Build();
  33. await mqttClient.DisconnectAsync(mqttClientDisconnectOptions, CancellationToken.None);
  34. }
  35. }
  36. public static async Task Connect_Client_Timeout()
  37. {
  38. /*
  39. * This sample creates a simple MQTT client and connects to an invalid broker using a timeout.
  40. *
  41. * This is a modified version of the sample _Connect_Client_! See other sample for more details.
  42. */
  43. var mqttFactory = new MqttFactory();
  44. using (var mqttClient = mqttFactory.CreateMqttClient())
  45. {
  46. var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1").Build();
  47. try
  48. {
  49. using (var timeoutToken = new CancellationTokenSource(TimeSpan.FromSeconds(1)))
  50. {
  51. await mqttClient.ConnectAsync(mqttClientOptions, timeoutToken.Token);
  52. }
  53. }
  54. catch (OperationCanceledException)
  55. {
  56. Console.WriteLine("Timeout while connecting.");
  57. }
  58. }
  59. }
  60. public static async Task Connect_Client_Using_MQTTv5()
  61. {
  62. /*
  63. * This sample creates a simple MQTT client and connects to a public broker using MQTTv5.
  64. *
  65. * This is a modified version of the sample _Connect_Client_! See other sample for more details.
  66. */
  67. var mqttFactory = new MqttFactory();
  68. using (var mqttClient = mqttFactory.CreateMqttClient())
  69. {
  70. var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer("broker.hivemq.com").WithProtocolVersion(MqttProtocolVersion.V500).Build();
  71. // In MQTTv5 the response contains much more information.
  72. var response = await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
  73. Console.WriteLine("The MQTT client is connected.");
  74. response.DumpToConsole();
  75. }
  76. }
  77. public static async Task Connect_Client_Using_TLS_1_2()
  78. {
  79. /*
  80. * This sample creates a simple MQTT client and connects to a public broker using TLS 1.2 encryption.
  81. *
  82. * This is a modified version of the sample _Connect_Client_! See other sample for more details.
  83. */
  84. var mqttFactory = new MqttFactory();
  85. using (var mqttClient = mqttFactory.CreateMqttClient())
  86. {
  87. var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer("mqtt.fluux.io")
  88. .WithTls(
  89. o =>
  90. {
  91. o.SslProtocol = SslProtocols.Tls12;
  92. })
  93. .Build();
  94. await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
  95. Console.WriteLine("The MQTT client is connected.");
  96. }
  97. }
  98. public static async Task Connect_Client_Using_WebSockets()
  99. {
  100. /*
  101. * This sample creates a simple MQTT client and connects to a public broker using a WebSocket connection.
  102. *
  103. * This is a modified version of the sample _Connect_Client_! See other sample for more details.
  104. */
  105. var mqttFactory = new MqttFactory();
  106. using (var mqttClient = mqttFactory.CreateMqttClient())
  107. {
  108. var mqttClientOptions = new MqttClientOptionsBuilder().WithWebSocketServer("broker.hivemq.com:8000/mqtt").Build();
  109. var response = await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
  110. Console.WriteLine("The MQTT client is connected.");
  111. response.DumpToConsole();
  112. }
  113. }
  114. public static async Task Connect_Client_With_TLS_Encryption()
  115. {
  116. /*
  117. * This sample creates a simple MQTT client and connects to a public broker with enabled TLS encryption.
  118. *
  119. * This is a modified version of the sample _Connect_Client_! See other sample for more details.
  120. */
  121. var mqttFactory = new MqttFactory();
  122. using (var mqttClient = mqttFactory.CreateMqttClient())
  123. {
  124. var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer("test.mosquitto.org", 8883)
  125. .WithTls(
  126. o =>
  127. {
  128. o.SslProtocol = SslProtocols.Tls12; // The default value is determined by the OS. Set manually to force version.
  129. })
  130. .Build();
  131. // In MQTTv5 the response contains much more information.
  132. var response = await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
  133. Console.WriteLine("The MQTT client is connected.");
  134. response.DumpToConsole();
  135. }
  136. }
  137. public static async Task Ping_Server()
  138. {
  139. /*
  140. * This sample sends a PINGREQ packet to the server and waits for a reply.
  141. *
  142. * This is only supported in METTv5.0.0+.
  143. */
  144. var mqttFactory = new MqttFactory();
  145. using (var mqttClient = mqttFactory.CreateMqttClient())
  146. {
  147. var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer("broker.hivemq.com").Build();
  148. await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
  149. // This will throw an exception if the server does not reply.
  150. await mqttClient.PingAsync(CancellationToken.None);
  151. Console.WriteLine("The MQTT server replied to the ping request.");
  152. }
  153. }
  154. public static async Task Reconnect_Using_Event()
  155. {
  156. /*
  157. * This sample shows how to reconnect when the connection was dropped.
  158. * This approach uses one of the events from the client.
  159. * This approach has a risk of dead locks! Consider using the timer approach (see sample).
  160. */
  161. var mqttFactory = new MqttFactory();
  162. using (var mqttClient = mqttFactory.CreateMqttClient())
  163. {
  164. var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer("broker.hivemq.com").Build();
  165. mqttClient.DisconnectedAsync += async e =>
  166. {
  167. if (e.ClientWasConnected)
  168. {
  169. // Use the current options as the new options.
  170. await mqttClient.ConnectAsync(mqttClient.Options);
  171. }
  172. };
  173. await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
  174. }
  175. }
  176. public static void Reconnect_Using_Timer()
  177. {
  178. /*
  179. * This sample shows how to reconnect when the connection was dropped.
  180. * This approach uses a custom Task/Thread which will monitor the connection status.
  181. * This is the recommended way but requires more custom code!
  182. */
  183. var mqttFactory = new MqttFactory();
  184. using (var mqttClient = mqttFactory.CreateMqttClient())
  185. {
  186. var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer("broker.hivemq.com").Build();
  187. _ = Task.Run(
  188. async () =>
  189. {
  190. // User proper cancellation and no while(true).
  191. while (true)
  192. {
  193. try
  194. {
  195. // This code will also do the very first connect! So no call to _ConnectAsync_ is required
  196. // in the first place.
  197. if (!mqttClient.IsConnected)
  198. {
  199. await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
  200. // Subscribe to topics when session is clean etc.
  201. Console.WriteLine("The MQTT client is connected.");
  202. }
  203. }
  204. catch
  205. {
  206. // Handle the exception properly (logging etc.).
  207. }
  208. finally
  209. {
  210. // Check the connection state every 5 seconds and perform a reconnect if required.
  211. await Task.Delay(TimeSpan.FromSeconds(5));
  212. }
  213. }
  214. });
  215. }
  216. }
  217. }