mirror of
https://github.com/dotnet/MQTTnet.git
synced 2026-10-19 02:53:06 +08:00
added aspnetcore package and adapted sample app
This commit is contained in:
@@ -2,10 +2,11 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netcoreapp2.0</TargetFramework>
|
||||
<TypeScriptToolsVersion>2.3</TypeScriptToolsVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="wwwroot\" />
|
||||
<Content Remove="wwwroot\app\app.ts" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -13,8 +14,11 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\Frameworks\MQTTnet.Netstandard\MQTTnet.NetStandard.csproj" />
|
||||
<ProjectReference Include="..\..\MQTTnet.Core\MQTTnet.Core.csproj" />
|
||||
<ProjectReference Include="..\..\Frameworks\MQTTnet.AspnetCore\MQTTnet.AspnetCore.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<TypeScriptCompile Include="wwwroot\app\app.ts" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.WebSockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Core.Adapter;
|
||||
using MQTTnet.Core.Channel;
|
||||
using MQTTnet.Core.Serializer;
|
||||
using MQTTnet.Core.Server;
|
||||
using MQTTnet.Implementations;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace MQTTnet.TestApp.AspNetCore2
|
||||
{
|
||||
public class MqttWebSocketServerAdapter : IMqttServerAdapter, IDisposable
|
||||
{
|
||||
private readonly ILogger<MqttWebSocketServerAdapter> _logger;
|
||||
private readonly IMqttCommunicationAdapterFactory _mqttCommunicationAdapterFactory;
|
||||
|
||||
public MqttWebSocketServerAdapter(ILogger<MqttWebSocketServerAdapter> logger, IMqttCommunicationAdapterFactory mqttCommunicationAdapterFactory)
|
||||
{
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_mqttCommunicationAdapterFactory = mqttCommunicationAdapterFactory ?? throw new ArgumentNullException(nameof(mqttCommunicationAdapterFactory));
|
||||
}
|
||||
|
||||
public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
|
||||
|
||||
public Task StartAsync(MqttServerOptions options)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task StopAsync()
|
||||
{
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
public Task AcceptWebSocketAsync(WebSocket webSocket)
|
||||
{
|
||||
if (webSocket == null) throw new ArgumentNullException(nameof(webSocket));
|
||||
|
||||
var channel = new MqttWebSocketServerChannel(webSocket);
|
||||
var clientAdapter = _mqttCommunicationAdapterFactory.CreateServerMqttCommunicationAdapter(channel);
|
||||
|
||||
var eventArgs = new MqttServerAdapterClientAcceptedEventArgs(clientAdapter);
|
||||
ClientAccepted?.Invoke(this, eventArgs);
|
||||
return eventArgs.SessionTask;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
StopAsync();
|
||||
}
|
||||
|
||||
private class MqttWebSocketServerChannel : IMqttCommunicationChannel, IDisposable
|
||||
{
|
||||
private readonly WebSocket _webSocket;
|
||||
|
||||
public MqttWebSocketServerChannel(WebSocket webSocket)
|
||||
{
|
||||
_webSocket = webSocket ?? throw new ArgumentNullException(nameof(webSocket));
|
||||
|
||||
RawReceiveStream = new WebSocketStream(_webSocket);
|
||||
}
|
||||
|
||||
public Stream SendStream => RawReceiveStream;
|
||||
public Stream ReceiveStream => RawReceiveStream;
|
||||
public Stream RawReceiveStream { get; }
|
||||
|
||||
public Task ConnectAsync()
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task DisconnectAsync()
|
||||
{
|
||||
RawReceiveStream?.Dispose();
|
||||
|
||||
if (_webSocket == null)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
return _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
RawReceiveStream?.Dispose();
|
||||
SendStream?.Dispose();
|
||||
ReceiveStream?.Dispose();
|
||||
|
||||
_webSocket?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.FileProviders;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using MQTTnet.Core.Adapter;
|
||||
using MQTTnet.Core.Server;
|
||||
using MQTTnet.AspnetCore;
|
||||
using MQTTnet.Core;
|
||||
|
||||
namespace MQTTnet.TestApp.AspNetCore2
|
||||
{
|
||||
@@ -13,35 +15,47 @@ namespace MQTTnet.TestApp.AspNetCore2
|
||||
{
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
services.AddMqttServer();
|
||||
services.AddSingleton<MqttWebSocketServerAdapter>();
|
||||
services.AddSingleton<IMqttServerAdapter, MqttWebSocketServerAdapter>();
|
||||
services.AddHostedMqttServer();
|
||||
}
|
||||
|
||||
public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
|
||||
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
|
||||
{
|
||||
loggerFactory.AddConsole(LogLevel.Debug);
|
||||
loggerFactory.AddDebug();
|
||||
|
||||
var adapter = app.ApplicationServices.GetService<MqttWebSocketServerAdapter>();
|
||||
var mqttServer = app.ApplicationServices.GetService<IMqttServer>();
|
||||
await mqttServer.StartAsync();
|
||||
|
||||
app.UseWebSockets();
|
||||
app.Use(async (context, next) =>
|
||||
app.UseMqttEndpoint();
|
||||
app.UseMqttServer(async server =>
|
||||
{
|
||||
if (context.WebSockets.IsWebSocketRequest)
|
||||
var msg = new MqttApplicationMessageBuilder()
|
||||
.WithPayload("Mqtt is Awesome")
|
||||
.WithTopic("message")
|
||||
.Build();
|
||||
|
||||
while (true)
|
||||
{
|
||||
using (var webSocket = await context.WebSockets.AcceptWebSocketAsync())
|
||||
{
|
||||
await adapter.AcceptWebSocketAsync(webSocket);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
await next();
|
||||
server.Publish(msg);
|
||||
await Task.Delay(TimeSpan.FromSeconds(2));
|
||||
}
|
||||
});
|
||||
|
||||
app.Use((context, next) =>
|
||||
{
|
||||
if (context.Request.Path == "/")
|
||||
{
|
||||
context.Request.Path = "/Index.html";
|
||||
}
|
||||
|
||||
return next();
|
||||
});
|
||||
|
||||
app.UseStaticFiles();
|
||||
|
||||
|
||||
app.UseStaticFiles( new StaticFileOptions()
|
||||
{
|
||||
RequestPath = "/node_modules",
|
||||
FileProvider = new PhysicalFileProvider( Path.Combine(env.ContentRootPath, "node_modules" ) )
|
||||
} );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"name": "mqtt.test",
|
||||
"private": true,
|
||||
"devDependencies": {
|
||||
},
|
||||
|
||||
"dependencies": {
|
||||
"mqtt": "2.13.1",
|
||||
"@types/node": "8.0.46",
|
||||
"systemjs": "0.20.19",
|
||||
"typescript": "2.3.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"noImplicitAny": false,
|
||||
"noEmitOnError": true,
|
||||
"removeComments": false,
|
||||
"sourceMap": true,
|
||||
"target": "es5"
|
||||
},
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>MQTT test</title>
|
||||
</head>
|
||||
<body>
|
||||
<script src="node_modules/systemjs/dist/system.js"></script>
|
||||
<script>
|
||||
System.config({
|
||||
packages: {
|
||||
'': {
|
||||
defaultExtension: 'js'
|
||||
}
|
||||
},
|
||||
map: {
|
||||
mqtt: 'node_modules/mqtt/dist/mqtt.min'
|
||||
}
|
||||
});
|
||||
System.import('app/app');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,16 @@
|
||||
import { connect } from "mqtt";
|
||||
|
||||
var client = connect('ws://' + location.host + '/mqtt',
|
||||
{
|
||||
clientId: "client1",
|
||||
});
|
||||
|
||||
client.on('connect', () => {
|
||||
client.subscribe('presence');
|
||||
client.publish('presence', 'Hello mqtt');
|
||||
});
|
||||
|
||||
client.on('message', (topic, message) => {
|
||||
// message is Buffer
|
||||
console.log(message.toString());
|
||||
})
|
||||
Reference in New Issue
Block a user