public async Task <IMqttServer> StartServer(MqttServerOptionsBuilder options) { var server = CreateServer(); options.WithDefaultEndpointPort(ServerPort); options.WithMaxPendingMessagesPerClient(int.MaxValue); await server.StartAsync(options.Build()); return(server); }
public async Task <IMqttServer> StartServerAsync(MqttServerOptionsBuilder options) { if (Server != null) { throw new InvalidOperationException("Server already started."); } Server = new TestServerWrapper(_mqttFactory.CreateMqttServer(_serverLogger), TestContext, this); await Server.StartAsync(options.WithDefaultEndpointPort(ServerPort).Build()); return(Server); }
private IMqttServerOptions CreateMqttServerOptions() { var options = new MqttServerOptionsBuilder() .WithMaxPendingMessagesPerClient(_settings.MaxPendingMessagesPerClient) .WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(_settings.CommunicationTimeout)) .WithConnectionValidator(_mqttConnectionValidator) .WithStorage(_mqttServerStorage); // Configure unencrypted connections if (_settings.TcpEndPoint.Enabled) { options.WithDefaultEndpoint(); if (_settings.TcpEndPoint.TryReadIPv4(out var address4)) { options.WithDefaultEndpointBoundIPAddress(address4); } if (_settings.TcpEndPoint.TryReadIPv6(out var address6)) { options.WithDefaultEndpointBoundIPV6Address(address6); } if (_settings.TcpEndPoint.Port > 0) { options.WithDefaultEndpointPort(_settings.TcpEndPoint.Port); } } else { options.WithoutDefaultEndpoint(); } if (_settings.ConnectionBacklog > 0) { options.WithConnectionBacklog(_settings.ConnectionBacklog); } if (_settings.EnablePersistentSessions) { options.WithPersistentSessions(); } if (_settings.UseOriginalReseiverClientId) { options.WithApplicationMessageInterceptor(_messageInterceptor); } return(options.Build()); }
public void changeServerConfig(ServerConfigData MQTTConfigData) { _theAuthenticator = MQTTConfigData.Authenticator; _ServerConfiguration = new MqttServerOptionsBuilder(); _ServerConfiguration.WithConnectionValidator(this); _ServerConfiguration.WithApplicationMessageInterceptor(this); _ServerConfiguration.WithSubscriptionInterceptor(this); _ServerConfiguration.WithClientId("Server"); _ServerConfiguration.WithDefaultEndpointBoundIPAddress(MQTTConfigData.listenAdress); _ServerConfiguration.WithDefaultEndpointPort(MQTTConfigData.Port); _ServerConfiguration.WithMaxPendingMessagesPerClient(FedNetConstante.MAX_MESSAGE_PENDING); _logSystem.Info("reinitialisation finnised !!"); }
public async Task <MqttServer> StartServer(MqttServerOptionsBuilder optionsBuilder) { optionsBuilder.WithDefaultEndpoint(); optionsBuilder.WithDefaultEndpointPort(ServerPort); optionsBuilder.WithMaxPendingMessagesPerClient(int.MaxValue); var options = optionsBuilder.Build(); var server = CreateServer(options); await server.StartAsync(); // The OS has chosen the port to we have to properly expose it to the tests. ServerPort = options.DefaultEndpointOptions.Port; return(server); }
/// <summary> /// 开启服务 /// </summary> private async Task <string> CreateMQTTServer(int port) { var optionsBuilder = new MqttServerOptionsBuilder(); try { //在 MqttServerOptions 选项中,你可以使用 ConnectionValidator 来对客户端连接进行验证。比如客户端ID标识 ClientId,用户名 Username 和密码 Password 等。 optionsBuilder.WithConnectionValidator(c => { try { if (LoginEvent != null) { LoginEvent?.Invoke(c); } else { c.ReturnCode = MqttConnectReturnCode.ConnectionAccepted; } } catch { c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword; return; } }); //指定端口 optionsBuilder.WithDefaultEndpointPort(port); //连接记录数,默认 一般为2000 //optionsBuilder.WithConnectionBacklog(2000); mqttServer = new MqttFactory().CreateMqttServer(); // 客户端支持 Connected、Disconnected 和 ApplicationMessageReceived 事件,用来处理客户端与服务端连接、客户端从服务端断开以及客户端收到消息的事情。 //其中 ClientConnected 和 ClientDisconnected 事件的事件参数一个客户端连接对象 ConnectedMqttClient,通过该对象可以获取客户端ID标识 ClientId 和 MQTT 版本 ProtocolVersion。 mqttServer.ClientConnected += MqttServer_ClientConnected; mqttServer.ClientDisconnected += MqttServer_ClientDisconnected; //ApplicationMessageReceived 的事件参数包含了客户端ID标识 ClientId 和 MQTT 应用消息 MqttApplicationMessage 对象,通过该对象可以获取主题 Topic、QoS QualityOfServiceLevel 和消息内容 Payload 等信息。 mqttServer.ApplicationMessageReceived += MqttServer_ApplicationMessageReceived; } catch (Exception ex) { return("MQTT服务创建失败>" + ex.Message); } await mqttServer.StartAsync(optionsBuilder.Build()); return("MQTT服务<0.0.0.0:" + port + ">已启动"); }
private static async Task MainAsync(string[] args) { Settings = SettingManager.ReadConfiguration(args); IMqttServer broker = null; MqttServerOptionsBuilder optionsBuilder = new MqttServerOptionsBuilder(); // TLS Support (X509Certificate2, string)tuple = GetBrokerCertificate(); //MqttTcpChannel.CustomCertificateValidationCallback += CustomCertificateValidationCallback; if (Settings.Broker.UseTLS) { Logger.Info("TLS v1.2 requested. Trying to get Broker Certifacte."); } if (Settings.Broker.UseTLS && tuple.Item1 != null) { Logger.Info("Found certificate:"); string san = GetSANFromCert(tuple.Item1); Logger.Info("Subject Alternative Names from Certifacate:"); Logger.Info(san); Logger.Info(tuple.Item1); optionsBuilder = optionsBuilder .WithEncryptedEndpoint() .WithEncryptedEndpointPort(8883) .WithEncryptionSslProtocol(SslProtocols.Tls12) .WithEncryptionCertificate(tuple.Item1.Export(X509ContentType.SerializedCert, tuple.Item2)); if (Settings.Broker.UseMutualAuth) { //broker = new MqttBroker(brokerCertificate, MqttSslProtocols.TLSv1_2, ValidateClientCertificate, UserCertificateSelectionCallback); } } else { Logger.Info("No encryption used."); optionsBuilder = optionsBuilder.WithDefaultEndpointPort(1883); } optionsBuilder = optionsBuilder.WithConnectionValidator(ValidateUserAndPassword); broker = new MqttFactory().CreateMqttServer(); IMqttServerOptions options = optionsBuilder.Build(); await broker.StartAsync(options); Console.ReadKey(); }
public async Task <IMqttServer> StartServerAsync(MqttServerOptionsBuilder options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } if (Server != null) { throw new InvalidOperationException("Server already started."); } Server = new TestServerWrapper(_mqttFactory.CreateMqttServer(ServerLogger), TestContext, this); options.WithDefaultEndpointPort(ServerPort); options.WithMaxPendingMessagesPerClient(int.MaxValue); await Server.StartAsync(options.Build()).ConfigureAwait(false); return(Server); }
public FedNetServer(ServerConfigData MQTTConfigData, IFedNetLogger newlogSystem = null) { _logSystem = newlogSystem; if (_logSystem == null) { _logSystem = new DefaultLogger(); } _theAuthenticator = MQTTConfigData.Authenticator; _ServerConfiguration = new MqttServerOptionsBuilder(); _ServerConfiguration.WithConnectionValidator(this); _ServerConfiguration.WithApplicationMessageInterceptor(this); _ServerConfiguration.WithSubscriptionInterceptor(this); _ServerConfiguration.WithClientId("Server"); _ServerConfiguration.WithDefaultEndpointBoundIPAddress(MQTTConfigData.listenAdress); _ServerConfiguration.WithDefaultEndpointPort(MQTTConfigData.Port); _ServerConfiguration.WithMaxPendingMessagesPerClient(FedNetConstante.MAX_MESSAGE_PENDING); _theClientList = new List <ClientData>(); _theGameServer = new MqttFactory().CreateMqttServer(); _theGameServer.UseApplicationMessageReceivedHandler(e => { if (e.ClientId == "" || e.ClientId == " " || e.ClientId == null) { return; } if (MessageReceived != null) { MessageReceived.Invoke(this, Message.getMessage(e.ApplicationMessage)); } }); _theGameServer.UseClientConnectedHandler(e => { _logSystem.Info("new client connected : " + e.ClientId); //_theGameServer.SubscribeAsync("Server", FedNetConstante.CLIENT_TO_SERVER + FedNetConstante.DEFAULT_TOPIC_SEPARATOR + FedNetConstante.DEFAULT_TOPIC_JOKER, (MqttQualityOfServiceLevel)FedNetConstante.PRIORITY_SERVER_TO_CLIENT); }); _theGameServer.StartedHandler = this; _theGameServer.StoppedHandler = this; _theGameServer.ClientDisconnectedHandler = this; _logSystem.Info("initialisation finished !!"); }
public void Start(out string errMsg) { errMsg = ""; if (IsRuning) { return; } if (this.mqttParam == null) { errMsg = "MQTT服务启动失败,没有指明服务所需参数"; return; } if (mqttServer == null) { try { mqttServer.StopAsync(); mqttServer = null; } catch { } } // MQTT 动态库本身已经实现异步启动,这里不用在用异步调用了 var optionsBuilder = new MqttServerOptionsBuilder(); try { //在 MqttServerOptions 选项中,你可以使用 ConnectionValidator 来对客户端连接进行验证。 //比如客户端ID标识 ClientId,用户名 Username 和密码 Password 等。 optionsBuilder.WithConnectionValidator(ClientCheck); //指定 ip地址,默认为本地 optionsBuilder.WithDefaultEndpointBoundIPAddress(IPAddress.Parse(this.mqttParam.ip)); //指定端口 optionsBuilder.WithDefaultEndpointPort(this.mqttParam.port); //连接记录数,默认 一般为2000 //optionsBuilder.WithConnectionBacklog(2000); mqttServer = new MqttFactory().CreateMqttServer() as MqttServer; // 客户端支持 Connected、Disconnected 和 ApplicationMessageReceived 事件, //用来处理客户端与服务端连接、客户端从服务端断开以及客户端收到消息的事情。 //其中 ClientConnected 和 ClientDisconnected 事件的事件参数一个客户端连接对象 ConnectedMqttClient, //通过该对象可以获取客户端ID标识 ClientId 和 MQTT 版本 ProtocolVersion。 mqttServer.ClientConnected += MqttServer_ClientConnected; mqttServer.ClientDisconnected += MqttServer_ClientDisconnected; //ApplicationMessageReceived 的事件参数包含了客户端ID标识 ClientId 和 MQTT 应用消息 MqttApplicationMessage 对象, //通过该对象可以获取主题 Topic、QoS QualityOfServiceLevel 和消息内容 Payload 等信息。 mqttServer.ApplicationMessageReceived += MqttServer_ApplicationMessageReceived; } catch (Exception ex) { // log.Info("创建Mqtt服务,连接客户端的Id长度过短(不得小于5),或不是指定的合法客户端(以Eohi_开头)"); errMsg = "创建MQTT服务失败:" + ex.Message; return; } Task task = mqttServer.StartAsync(optionsBuilder.Build()); task.Wait(5000); IsRuning = task.IsCompleted; }
IMqttServerOptions CreateMqttServerOptions() { var options = new MqttServerOptionsBuilder() .WithMaxPendingMessagesPerClient(_settings.MaxPendingMessagesPerClient) .WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(_settings.CommunicationTimeout)) .WithConnectionValidator(_mqttConnectionValidator) .WithApplicationMessageInterceptor(_mqttApplicationMessageInterceptor) .WithSubscriptionInterceptor(_mqttSubscriptionInterceptor) .WithUnsubscriptionInterceptor(_mqttUnsubscriptionInterceptor) .WithStorage(_mqttServerStorage); // Configure unencrypted connections if (_settings.TcpEndPoint.Enabled) { options.WithDefaultEndpoint(); if (_settings.TcpEndPoint.TryReadIPv4(out var address4)) { options.WithDefaultEndpointBoundIPAddress(address4); } if (_settings.TcpEndPoint.TryReadIPv6(out var address6)) { options.WithDefaultEndpointBoundIPV6Address(address6); } if (_settings.TcpEndPoint.Port > 0) { options.WithDefaultEndpointPort(_settings.TcpEndPoint.Port); } } else { options.WithoutDefaultEndpoint(); } // Configure encrypted connections if (_settings.EncryptedTcpEndPoint.Enabled) { #if NETCOREAPP3_1 || NET5_0 options .WithEncryptedEndpoint() .WithEncryptionSslProtocol(SslProtocols.Tls13); #else options .WithEncryptedEndpoint() .WithEncryptionSslProtocol(SslProtocols.Tls12); #endif if (!string.IsNullOrEmpty(_settings.EncryptedTcpEndPoint?.Certificate?.Path)) { IMqttServerCertificateCredentials certificateCredentials = null; if (!string.IsNullOrEmpty(_settings.EncryptedTcpEndPoint?.Certificate?.Password)) { certificateCredentials = new MqttServerCertificateCredentials { Password = _settings.EncryptedTcpEndPoint.Certificate.Password }; } options.WithEncryptionCertificate(_settings.EncryptedTcpEndPoint.Certificate.ReadCertificate(), certificateCredentials); } if (_settings.EncryptedTcpEndPoint.TryReadIPv4(out var address4)) { options.WithEncryptedEndpointBoundIPAddress(address4); } if (_settings.EncryptedTcpEndPoint.TryReadIPv6(out var address6)) { options.WithEncryptedEndpointBoundIPV6Address(address6); } if (_settings.EncryptedTcpEndPoint.Port > 0) { options.WithEncryptedEndpointPort(_settings.EncryptedTcpEndPoint.Port); } } else { options.WithoutEncryptedEndpoint(); } if (_settings.ConnectionBacklog > 0) { options.WithConnectionBacklog(_settings.ConnectionBacklog); } if (_settings.EnablePersistentSessions) { options.WithPersistentSessions(); } return(options.Build()); }
static Igloo15MqttServer InitializeServer(Options config, ILoggerFactory factory) { Igloo15MqttServer server = null; try { MqttServerOptionsBuilder serverBuilder = new MqttServerOptionsBuilder(); if (config.Encrypted && File.Exists(config.CertificateLocation)) { if (config.IPAddress == "Any") { serverBuilder.WithEncryptedEndpoint(); } else if (IPAddress.TryParse(config.IPAddress, out IPAddress address)) { serverBuilder.WithEncryptedEndpointBoundIPAddress(address); } else { _logger.LogWarning($"Failed to parse provided IP Address : {config.IPAddress} using default"); serverBuilder.WithEncryptedEndpoint(); } serverBuilder.WithEncryptedEndpointPort(config.Port); var certificate = new X509Certificate2(config.CertificateLocation, config.CertificatePassword); var certBytes = certificate.Export(X509ContentType.Cert); serverBuilder.WithEncryptionCertificate(certBytes); } else { if (config.IPAddress == "Any") { serverBuilder.WithDefaultEndpoint(); } else if (IPAddress.TryParse(config.IPAddress, out IPAddress address)) { serverBuilder.WithDefaultEndpointBoundIPAddress(address); } else { _logger.LogWarning("Failed to parse provided IP Address : {IPAddress} using default", config.IPAddress); serverBuilder.WithDefaultEndpoint(); } serverBuilder.WithDefaultEndpointPort(config.Port); } if (config.Persistent) { serverBuilder.WithPersistentSessions(); } if (!String.IsNullOrEmpty(config.MessageStorageLocation)) { serverBuilder.WithStorage(new RetainedMessageHandler(config.MessageStorageLocation)); } if (config.ShowSubscriptions) { serverBuilder.WithSubscriptionInterceptor(_interceptors.SubscriptionInterceptor); } if (config.ShowMessages) { serverBuilder.WithApplicationMessageInterceptor(_interceptors.MessageInterceptor); } if (config.ShowClientConnections) { serverBuilder.WithConnectionValidator(_interceptors.ConnectionInterceptor); } serverBuilder .WithConnectionBacklog(config.ConnectionBacklog) .WithMaxPendingMessagesPerClient(config.MaxPendingMessagesPerClient) .WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(config.CommunicationTimeout)); server = new Igloo15MqttServer(serverBuilder.Build(), factory); } catch (Exception e) { _logger.LogError(e, "Exception occured during Initialization of Server"); return(null); } return(server); }
IMqttServerOptions CreateMqttServerOptions() { // Create client id if none provided var cid = string.IsNullOrWhiteSpace(_settings.BrokerClientId) ? Guid.NewGuid().ToString("N").ToUpper() : _settings.BrokerClientId; var options = new MqttServerOptionsBuilder() .WithMaxPendingMessagesPerClient(_settings.MaxPendingMessagesPerClient) .WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(_settings.CommunicationTimeout)) .WithConnectionValidator(_mqttConnectionValidator) .WithApplicationMessageInterceptor(_mqttApplicationMessageInterceptor) .WithSubscriptionInterceptor(_mqttSubscriptionInterceptor) .WithUnsubscriptionInterceptor(_mqttUnsubscriptionInterceptor) .WithClientId(cid); // Configure unencrypted connections if (_settings.TcpEndPoint.Enabled) { options.WithDefaultEndpoint(); if (_settings.TcpEndPoint.TryReadIPv4(out var address4)) { options.WithDefaultEndpointBoundIPAddress(address4); } if (_settings.TcpEndPoint.TryReadIPv6(out var address6)) { options.WithDefaultEndpointBoundIPV6Address(address6); } if (_settings.TcpEndPoint.Port > 0) { options.WithDefaultEndpointPort(_settings.TcpEndPoint.Port); _logger.LogInformation($"MQTT Broker '{_settings.BrokerName}' listening on TCP port {_settings.TcpEndPoint.Port}, ClientID: {cid}"); } } else { options.WithoutDefaultEndpoint(); } // Configure encrypted connections if (_settings.EncryptedTcpEndPoint.Enabled) { options .WithEncryptedEndpoint() .WithEncryptionSslProtocol(SslProtocols.Tls13); if (!string.IsNullOrEmpty(_settings.EncryptedTcpEndPoint?.Certificate?.Path)) { IMqttServerCertificateCredentials certificateCredentials = null; if (!string.IsNullOrEmpty(_settings.EncryptedTcpEndPoint?.Certificate?.Password)) { certificateCredentials = new MqttServerCertificateCredentials { Password = _settings.EncryptedTcpEndPoint.Certificate.Password }; } options.WithEncryptionCertificate(_settings.EncryptedTcpEndPoint.Certificate.ReadCertificate(), certificateCredentials); } if (_settings.EncryptedTcpEndPoint.TryReadIPv4(out var address4)) { options.WithEncryptedEndpointBoundIPAddress(address4); } if (_settings.EncryptedTcpEndPoint.TryReadIPv6(out var address6)) { options.WithEncryptedEndpointBoundIPV6Address(address6); } if (_settings.EncryptedTcpEndPoint.Port > 0) { options.WithEncryptedEndpointPort(_settings.EncryptedTcpEndPoint.Port); _logger.LogInformation($"MQTT Broker {_settings.BrokerName} listening on SSL port {_settings.TcpEndPoint.Port}"); } } else { options.WithoutEncryptedEndpoint(); } if (_settings.ConnectionBacklog > 0) { options.WithConnectionBacklog(_settings.ConnectionBacklog); } if (_settings.EnablePersistentSessions) { options.WithPersistentSessions(); } return(options.Build()); }
public void Start(out string errMsg) { errMsg = ""; if (IsRuning) { return; } if (this.mqttParam == null) { errMsg = "MQTT服务启动失败,没有指明服务所需参数"; return; } // 检查端口是否空闲 if (!IPTool.IsValidPort(this.mqttParam.port)) { errMsg = "数据发布服务器的监听端口被占用,请更换端口号"; return; } if (mqttServer == null) { try { mqttServer.StopAsync(); mqttServer = null; } catch { } } // MQTT 动态库本身已经实现异步启动,这里不用在用异步调用了 try { var optionsBuilder = new MqttServerOptionsBuilder(); // //在 MqttServerOptions 选项中,你可以使用 ConnectionValidator 来对客户端连接进行验证。 // //比如客户端ID标识 ClientId,用户名 Username 和密码 Password 等。 optionsBuilder.WithConnectionValidator(ClientCheck); //指定 ip地址,默认为本地 if (string.IsNullOrWhiteSpace(this.mqttParam.ip)) { optionsBuilder.WithDefaultEndpointBoundIPAddress(IPAddress.Parse(this.mqttParam.ip)); } else { optionsBuilder.WithDefaultEndpointBoundIPAddress(IPAddress.Any); } //指定端口 optionsBuilder.WithDefaultEndpointPort(this.mqttParam.port); // // optionsBuilder.WithConnectionBacklog(100).WithEncryptedEndpointBoundIPAddress(IPAddress.Any).WithEncryptedEndpointPort(9323); // var certificate = new X509Certificate(@"D:\ddd.cer", ""); //var options = optionsBuilder.Build(); // options.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert); // //ssl //var certificate = new X509Certificate(@"D:\ddd.cer", ""); //MqttServerOptions certifOption = new MqttServerOptions(); //certifOption.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert); //certifOption.TlsEndpointOptions.IsEnabled = true; //optionsBuilder.WithEncryptionCertificate(certifOption.TlsEndpointOptions.Certificate); // var optionsBuilder = new MqttServerOptionsBuilder() //.WithConnectionBacklog(100) //.WithEncryptedEndpointPort(1884) //.WithoutDefaultEndpoint(); var mqttServer = new MqttFactory().CreateMqttServer(); //连接记录数,默认 一般为2000 //optionsBuilder.WithConnectionBacklog(2000); mqttServer = new MqttFactory().CreateMqttServer() as MqttServer; // 客户端支持 Connected、Disconnected 和 ApplicationMessageReceived 事件, //用来处理客户端与服务端连接、客户端从服务端断开以及客户端收到消息的事情。 //其中 ClientConnected 和 ClientDisconnected 事件的事件参数一个客户端连接对象 ConnectedMqttClient, //通过该对象可以获取客户端ID标识 ClientId 和 MQTT 版本 ProtocolVersion。 mqttServer.ClientConnected += MqttServer_ClientConnected; mqttServer.ClientDisconnected += MqttServer_ClientDisconnected; //ApplicationMessageReceived 的事件参数包含了客户端ID标识 ClientId 和 MQTT 应用消息 MqttApplicationMessage 对象, //通过该对象可以获取主题 Topic、QoS QualityOfServiceLevel 和消息内容 Payload 等信息。 mqttServer.ApplicationMessageReceived += MqttServer_ApplicationMessageReceived; // Task task = mqttServer.StartAsync(options); Task task = mqttServer.StartAsync(optionsBuilder.Build()); task.Wait(5000); IsRuning = task.IsCompleted; } catch (Exception ex) { // log.Info("创建Mqtt服务,连接客户端的Id长度过短(不得小于5),或不是指定的合法客户端(以Eohi_开头)"); errMsg = "创建MQTT服务失败:" + ex.Message + "堆栈:" + ex.StackTrace; return; } //Task task = mqttServer.StartAsync(options); //// Task task = mqttServer.StartAsync(optionsBuilder.Build()); //task.Wait(5000); }