/trunk/WingMan/Communication/MQTTClient.cs |
@@ -0,0 +1,86 @@ |
using System; |
using System.Collections.Generic; |
using System.Linq; |
using System.Net; |
using System.Text; |
using System.Threading.Tasks; |
using MQTTnet; |
using MQTTnet.Client; |
using MQTTnet.Extensions.ManagedClient; |
|
namespace WingMan.Communication |
{ |
public class MQTTClient : IDisposable |
{ |
private IManagedMqttClient Client { get; set; } |
public bool ClientRunning { get; set; } |
|
public MQTTClient() |
{ |
Client = new MqttFactory().CreateManagedMqttClient(); |
} |
|
public async Task Start(IPAddress ipAddress, int port) |
{ |
// Setup and start a managed MQTT client. |
var options = new ManagedMqttClientOptionsBuilder() |
.WithAutoReconnectDelay(TimeSpan.FromSeconds(5)) |
.WithClientOptions(new MqttClientOptionsBuilder() |
.WithTcpServer(ipAddress.ToString(), port) |
.WithTls().Build()) |
.Build(); |
BindHandlers(); |
|
await Client.SubscribeAsync( |
new TopicFilterBuilder() |
.WithTopic("lobby") |
.WithTopic("exchange") |
.Build() |
); |
|
await Client.StartAsync(options); |
|
ClientRunning = true; |
} |
|
private void ClientOnApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e) |
{ |
|
} |
|
private void ClientOnConnected(object sender, MqttClientConnectedEventArgs e) |
{ |
|
} |
|
public async Task Stop() |
{ |
UnbindHandlers(); |
|
await Client.StopAsync(); |
|
ClientRunning = false; |
} |
|
public void Dispose() |
{ |
UnbindHandlers(); |
|
Client.StopAsync().Wait(); |
|
Client?.Dispose(); |
} |
|
public void BindHandlers() |
{ |
Client.Connected += ClientOnConnected; |
Client.ApplicationMessageReceived += ClientOnApplicationMessageReceived; |
} |
|
public void UnbindHandlers() |
{ |
Client.Connected -= ClientOnConnected; |
Client.ApplicationMessageReceived -= ClientOnApplicationMessageReceived; |
} |
} |
} |
/trunk/WingMan/Communication/MQTTServer.cs |
@@ -0,0 +1,40 @@ |
using System; |
using System.Collections.Generic; |
using System.Linq; |
using System.Net; |
using System.Text; |
using System.Threading.Tasks; |
using MQTTnet; |
using MQTTnet.Server; |
|
namespace WingMan.Host |
{ |
public class MQTTServer |
{ |
private IMqttServer Server { get; set; } |
public bool ServerRunning { get; set; } |
|
public MQTTServer() |
{ |
Server = new MqttFactory().CreateMqttServer(); |
} |
|
public async Task Stop() |
{ |
await Server.StopAsync().ConfigureAwait(false); |
|
ServerRunning = false; |
} |
|
public async Task Start(IPAddress ipAddress, int port) |
{ |
var optionsBuilder = new MqttServerOptionsBuilder() |
.WithDefaultEndpointBoundIPAddress(ipAddress) |
.WithDefaultEndpointPort(port); |
|
await Server.StartAsync(optionsBuilder.Build()).ConfigureAwait(false); |
|
ServerRunning = true; |
} |
} |
} |