Преглед изворни кода

Merge pull request #889 from PMExtra/feature-with-uri

Support MqttClientOptionsBuilder.WithConnectionUri()
release/3.x.x
Christian пре 4 година
committed by GitHub
родитељ
комит
6de28d32e4
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
3 измењених фајлова са 71 додато и 0 уклоњено
  1. +1
    -0
      Build/MQTTnet.nuspec
  2. +48
    -0
      Source/MQTTnet/Extensions/MqttClientOptionsBuilderExtension.cs
  3. +22
    -0
      Tests/MQTTnet.Core.Tests/MqttClientOptionsBuilder_Tests.cs

+ 1
- 0
Build/MQTTnet.nuspec Прегледај датотеку

@@ -22,6 +22,7 @@
* [Server] Added interceptor for unsubscriptions.
* [MQTTnet.Server] Added interceptor for unsubscriptions.
* [MQTTnet.AspNetCore] improved compatibility with AspNetCore 3.1
* [Client] Support WithConnectionUri to configure client (thanks to @PMExtra).
* [Server] Removed exceptions when user properties are set with MQTT protocol version 3.1
</releaseNotes>
<copyright>Copyright Christian Kratky 2016-2020</copyright>


+ 48
- 0
Source/MQTTnet/Extensions/MqttClientOptionsBuilderExtension.cs Прегледај датотеку

@@ -0,0 +1,48 @@
using System;
using System.Linq;
using MQTTnet.Client.Options;

namespace MQTTnet.Extensions
{
public static class MqttClientOptionsBuilderExtension
{
public static MqttClientOptionsBuilder WithConnectionUri(this MqttClientOptionsBuilder builder, Uri uri)
{
var port = uri.IsDefaultPort ? null : (int?) uri.Port;
switch (uri.Scheme.ToLower())
{
case "tcp":
case "mqtt":
builder.WithTcpServer(uri.Host, port);
break;

case "mqtts":
builder.WithTcpServer(uri.Host, port).WithTls();
break;

case "ws":
case "wss":
builder.WithWebSocketServer(uri.ToString());
break;

default:
throw new ArgumentException("Unexpected scheme in uri.");
}
if (!string.IsNullOrEmpty(uri.UserInfo))
{
var userInfo = uri.UserInfo.Split(':');
var username = userInfo[0];
var password = userInfo.Length > 1 ? userInfo[1] : "";
builder.WithCredentials(username, password);
}

return builder;
}

public static MqttClientOptionsBuilder WithConnectionUri(this MqttClientOptionsBuilder builder, string uri)
{
return WithConnectionUri(builder, new Uri(uri, UriKind.Absolute));
}
}
}

+ 22
- 0
Tests/MQTTnet.Core.Tests/MqttClientOptionsBuilder_Tests.cs Прегледај датотеку

@@ -0,0 +1,22 @@
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MQTTnet.Client.Options;
using MQTTnet.Extensions;

namespace MQTTnet.Tests
{
[TestClass]
public class MqttClientOptionsBuilder_Tests
{
[TestMethod]
public void WithConnectionUri_Credential_Test()
{
var options = new MqttClientOptionsBuilder()
.WithConnectionUri("mqtt://user:password@127.0.0.1")
.Build();
Assert.AreEqual("user", options.Credentials.Username);
Assert.IsTrue(Encoding.UTF8.GetBytes("password").SequenceEqual(options.Credentials.Password));
}
}
}

Loading…
Откажи
Сачувај