dotnet / MQTTnet

MQTTnet is a high performance .NET library for MQTT based communication. It provides a MQTT client and a MQTT server (broker). The implementation is based on the documentation from http://mqtt.org/.
MIT License
4.51k stars 1.07k forks source link

Connecting to MQTT broker using WebSocket #680

Closed TaherianuBeac closed 5 years ago

TaherianuBeac commented 5 years ago

I am trying to make a broker to communicate with it by WebSocket. I used this code but it wasn't successful. I cannot even connect to broker via WebSocket but I can connect via tcp (port 1883)

public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }

public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            //this adds a hosted mqtt server to the services
            services.AddHostedMqttServer(new MqttServerOptionsBuilder().Build());            

            //this adds tcp server support based on Microsoft.AspNetCore.Connections.Abstractions
            services.AddMqttConnectionHandler();

            //this adds websocket support
            services.AddMqttWebSocketServerAdapter();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            var mqttServer = new MqttFactory().CreateMqttServer();
            mqttServer.StartAsync(new MqttServerOptionsBuilder().Build());

            //app.UseMqttEndpoint();

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }

I also tried with app.UseMqttEndpoint(). I am using mqttnet version 3.0.4 and asp.net core 2.2.0 I'm using MQTTlens and MQTTBox as client. What did I do wrong?

JanEggers commented 5 years ago

please check out the code in https://github.com/chkr1011/MQTTnet/blob/master/Tests/MQTTnet.TestApp.AspNetCore2/

pakinmaksim-niuitmo commented 3 years ago

Try port 5000 to connect. in @JanEggers' comment, the code uses 5000 port for WebSockets (ws://localhost:5000/mqtt)

mstobo commented 2 years ago

Above link is broken

JanEggers commented 2 years ago

here is an updated link for anyone that didnt figure it out yet:

https://github.com/dotnet/MQTTnet/tree/master/Source/MQTTnet.AspTestApp