ASP.net Core MVC + REST server
See original GitHub issueDescribe your question
I’m trying to do a server REST and MQTT with ASP.net Core MVC for working with Unity3D. The REST server is working fine. I’m facing that issue when trying to connect to the server with WebSocket: QTTnet.Exceptions.MqttCommunicationException: Unable to connect to the remote server —> System.Net.WebSockets.WebSocketException: Unable to connect to the remote server
I tried for one week to make it work but I’m running out of ideas. I would be grateful if you guys can tell me what did I missed.
Versions: Microsoft.AspDotNetCore.App 3.1.2 Microsoft.NETCore.App 3.1.0 Microsoft.AspNetCore.Mvc.NewtonsoftJson 3.1.3 MQTTnet 3.0.11 MQTTnet.AspNetCore 3.0.11
The client connection part:
var id = SystemInfo.deviceUniqueIdentifier;
var factory = new MqttFactory();
this.mqttClient = factory.CreateMqttClient();
// WebSocket
var options = new MqttClientOptionsBuilder()
.WithClientId(id)
.WithWebSocketServer("ws://127.0.0.1:5000/mqtt")
.WithKeepAlivePeriod(TimeSpan.FromHours(24))
.WithKeepAliveSendInterval(TimeSpan.FromSeconds(5))
.WithCleanSession()
.Build();
mqttClient.UseDisconnectedHandler(async e => {
Debug.Log("### DISCONNECTED FROM SERVER ###");
await Task.Delay(TimeSpan.FromSeconds(5));
try {
await mqttClient.ConnectAsync(options, CancellationToken.None); // Since 3.0.5 with CancellationToken
} catch (Exception ex) {
Debug.Log("### RECONNECTING FAILED ###");
Debug.Log(ex);
}
});
try {
await mqttClient.ConnectAsync(options, CancellationToken.None); // Since 3.0.5 with CancellationToken
} catch (Exception e) {
Debug.Log(e);
}
The server Programm class:
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
//CreateHostBuilder(args).Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => {
webBuilder.UseStartup<Startup>();
});
The server Configure Service:
public void ConfigureServices(IServiceCollection services)
{
// requires using Microsoft.Extensions.Options
services.Configure<DatabaseSettings>(
Configuration.GetSection(nameof(DatabaseSettings)));
services.AddSingleton<IDatabaseSettings>(sp =>
sp.GetRequiredService<IOptions<DatabaseSettings>>().Value);
// Add Services
services.AddSingleton<Service>();
// Add Controllers
services.AddControllers().AddNewtonsoftJson(options => options.UseMemberCasing());
// MQTT
services.AddSingleton<MqttService>();
services.AddHostedMqttServerWithServices(options => {
var s = options.ServiceProvider.GetRequiredService<MqttService>();
s.ConfigureMqttServerOptions(options);
});
services.AddMqttWebSocketServerAdapter();
services.AddMqttConnectionHandler();
}
The server Configure
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
// MQTT
_ = app.UseMqttEndpoint();
app.UseMqttServer(server => app.ApplicationServices.GetRequiredService<MqttService>().ConfigureMqttServer(server));
}
The server MQTT service witout all the implemented interfaces
public class MqttService : IMqttServerClientConnectedHandler, IMqttServerClientDisconnectedHandler, IMqttServerApplicationMessageInterceptor, IMqttServerConnectionValidator, IMqttServerStartedHandler
{
IMqttServer mqtt;
public void ConfigureMqttServerOptions(AspNetMqttServerOptionsBuilder options)
{
options.WithConnectionValidator(this);
options.WithApplicationMessageInterceptor(this);
}
public void ConfigureMqttServer(IMqttServer mqtt)
{
this.mqtt = mqtt;
mqtt.ClientConnectedHandler = this;
mqtt.ClientDisconnectedHandler = this;
}
Thanks in advance !
edit: changed the versions to 3.0.11
Issue Analytics
- State:
- Created 3 years ago
- Comments:5
Thanks for all your answers 😃 Because of some time pressure, I made it work by changing from WebSocket to TCP.
So here my working setup:
Startup.cs ConfigureServices
Startup.cs Configure
Program.cs
@JimmyPun610’s solution should work, as far as I can see from the examples 😃