Giter Site home page Giter Site logo

Comments (5)

shouhujishu avatar shouhujishu commented on May 23, 2024 1

Thanks for the help, I added WithDefaultEndpoint () and it works fine

from mqttnet.

SeppPenner avatar SeppPenner commented on May 23, 2024

I would recommend to build a background service following https://learn.microsoft.com/en-us/dotnet/core/extensions/windows-service and provide it within the startup:

service.AddSingleton<MyBackgroundService>();
service.AddHostedService(p => p.GetRequiredService<MyBackgroundService>());

from mqttnet.

shouhujishu avatar shouhujishu commented on May 23, 2024

I would recommend to build a background service following https://learn.microsoft.com/en-us/dotnet/core/extensions/windows-service and provide it within the startup:

service.AddSingleton<MyBackgroundService>();
service.AddHostedService(p => p.GetRequiredService<MyBackgroundService>());

Hello, test code output: StartAsync still does not open the port, IMqttNetLogger log has output: Started, and then there is no active content output.

public class IotMqttServer : IHostedService
{
    private MqttServer mMqtt;
    public IotMqttServer()
    {
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        try
        {
            var optionsBuilder = new MqttServerOptionsBuilder().WithConnectionBacklog(100).WithDefaultEndpointPort(87941);
            var mMqtt = new MqttFactory(new MyLogger()).CreateMqttServer(optionsBuilder.Build());
            await mMqtt.StartAsync();
            System.Diagnostics.Debug.WriteLine("StartAsync");
        }
        catch (Exception)
        {
        }
    }
    public async Task StopAsync(CancellationToken cancellationToken)
    {
        if (mMqtt != null)
        {
            if (mMqtt.IsStarted)
            {
                await mMqtt.StopAsync();
            }
        }
    }}
builder.Services.AddSingleton<IotMqttServer>();
builder.Services.AddHostedService(P=>P.GetRequiredService<IotMqttServer>());

from mqttnet.

SeppPenner avatar SeppPenner commented on May 23, 2024

@shouhujishu This is how I use it:

using MQTTnet;
using MQTTnet.Protocol;
using MQTTnet.Server;

/// <inheritdoc cref="BackgroundService"/>
public sealed class MqttBrokerService : BackgroundService
{
    /// <summary>
    /// The MQTT Server.
    /// </summary>
    public MqttServer MqttServer { get; internal set; }

    /// <summary>
    /// Initializes a new instance of the <see cref="MqttBrokerService"/> class.
    /// </summary>
    public MqttBrokerService()
    {
        var mqttFactory = new MqttFactory();
        var mqttServerOptions = mqttFactory
            .CreateServerOptionsBuilder()
            .WithDefaultEndpoint()
            .WithDefaultEndpointBoundIPAddress(IPAddress.Parse("0.0.0.0"))
            .WithDefaultEndpointPort(1883)
            .Build();
        this.MqttServer = mqttFactory.CreateMqttServer(mqttServerOptions);
    }

    /// <inheritdoc cref="BackgroundService"/>
    public override async Task StartAsync(CancellationToken cancellationToken)
    {
        this.logger.Information("Starting MQTT server on port {Port}", 1883);

        // Start the MQTT server
        await this.MqttServer.StartAsync();

        this.logger.Information("MQTT server has started");
        await base.StartAsync(cancellationToken);
    }

    /// <inheritdoc cref="BackgroundService"/>
    public override async Task StopAsync(CancellationToken cancellationToken)
    {
        this.logger.Information("Stopping MQTT server");
        await this.MqttServer.StopAsync();
        await base.StopAsync(cancellationToken);
        this.logger.Information("MQTT server is stopped");
    }

    /// <inheritdoc cref="BackgroundService"/>
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
            this.logger.Information("MQTT server is running");
        }
    }
}

I guess, you were missing .WithDefaultEndpoint() and .WithDefaultEndpointBoundIPAddress(IPAddress.Parse("0.0.0.0")). Note: 0.0.0.0 as IP address is needed if you want to have the broker accessible from outside the machine as well, else you can use 127.0.0.1 as well. You can change the port of 1883 to any other port, of course.

from mqttnet.

SeppPenner avatar SeppPenner commented on May 23, 2024

I guess, we can close this :)

from mqttnet.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.