Compare commits

...
20 Commits
Author SHA1 Message Date
Christian d5691346a9 Update MQTTnet.nuspec 2022-01-27 20:22:51 +01:00
HansM 0730f21d29 Merge pull request #1338 from alvin1221/public_broker_test
Thank you, this is indeed a bug.
2022-01-12 17:57:33 +01:00
alvin1221 6dfa7f0769 Fix incorrect TLS port of broker.emqx.io 2022-01-12 11:29:15 +08:00
Christian 27592f1643 Update MQTTnet.nuspec 2022-01-08 15:36:35 +01:00
Christian c6f4b59438 Increase delay for Keep Alive checks to decrease CPU load. 2022-01-08 15:35:47 +01:00
Christian b362b2afc2 Make logger parameters generic. 2022-01-08 14:35:25 +01:00
Christian 7a72a8d562 Update MQTTnet.nuspec 2022-01-08 14:07:57 +01:00
Günther Foidl bd40e10a66 Elide repeated Action-delegate allocation by caching it (#1324)
* Elide repeated Action-delegate allocation by caching it

Here C# compiler has too little knowledge about the usage of the delegate, we know better so cache it on our own to avoid the repeated allocation.

* Use conditional compilation
2022-01-08 14:00:39 +01:00
Christian 4b44a2b2b1 Remove appveyor. 2022-01-07 18:01:03 +01:00
Christian 215f24a95b Create CODE-OF-CONDUCT.md 2022-01-07 17:52:16 +01:00
Christian 72f9acdc20 Update CI 2022-01-06 20:55:20 +01:00
Christian 1e5390679f Update ci.yml 2022-01-06 20:41:18 +01:00
Christian 5cafce4345 Update ci.yml 2022-01-06 20:40:06 +01:00
Christian dfaf3dc31f Update ci.yml 2022-01-06 20:37:24 +01:00
Christian 3a9397c793 Update CI. 2022-01-06 20:36:12 +01:00
Christian 1cf4a7d6be Update ci.yml 2022-01-06 20:26:11 +01:00
Christian 180588c3a4 Update ci.yml 2022-01-06 20:18:04 +01:00
Christian bc4c86bebd Update ci.yml 2022-01-06 20:13:11 +01:00
Christian ea88a8c0de Update CI. 2022-01-06 20:10:42 +01:00
Günther Foidl d98129481a Fixed latent bug in MqttApplicationMessageBuilder.WithPayload stream overload (#1322) 2022-01-04 19:25:26 +01:00
29 changed files with 238 additions and 312 deletions
+34
View File
@@ -0,0 +1,34 @@
name: CI
on: [push]
jobs:
build:
runs-on: windows-latest
strategy:
matrix:
dotnet-version: ['6.0.x']
steps:
- uses: actions/checkout@v2
- name: Setup .NET Core SDK ${{ matrix.dotnet-version }}
uses: actions/setup-dotnet@v1.7.2
with:
dotnet-version: ${{ matrix.dotnet-version }}
- name: Build
shell: pwsh
run: |
Set-Location -Path "Build"
.\build.ps1 1.2.3 4.5.6-rc1
# - name: Install dependencies
# run: dotnet restore MQTTnet.sln
# - name: Build
# run: dotnet build --configuration Release --no-restore MQTTnet.sln
# - name: Test MQTTnet
# run: dotnet test --no-restore --verbosity normal Tests\MQTTnet.Core.Tests\MQTTnet.Tests.csproj
# - name: Test AspNetCore
# run: dotnet test --no-restore --verbosity normal Tests\MQTTnet.AspNetCore.Tests\MQTTnet.AspNetCore.Tests.csproj
-67
View File
@@ -1,67 +0,0 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: [ master ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ master ]
schedule:
- cron: '23 9 * * 6'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
language: [ 'csharp' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
# Learn more:
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
steps:
- name: Checkout repository
uses: actions/checkout@v2
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
-62
View File
@@ -1,62 +0,0 @@
# This is a basic workflow to help you get started with Actions
name: Deb Packaging
# Controls when the action will run.
on:
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Parse version
run: echo VERSION=$(grep '<Version>' Source/MQTTnet.Server/MQTTnet.Server.csproj | grep [0-9\.]* -o) >> $GITHUB_ENV
- name: Build MQTTnetServer
run: dotnet publish Source/MQTTnet.Server/MQTTnet.Server.csproj --configuration Release --self-contained --runtime linux-x64 --framework net5.0
- name: Set up installation directory
run: mkdir -p packaging/opt/MQTTnetServer
- name: Copy meta data
run: |
cp -R Build/deb-meta/* packaging/
chmod 755 packaging/DEBIAN/postinst
chmod 755 packaging/DEBIAN/postrm
chmod 755 packaging/DEBIAN/prerm
- name: Move artifacts to packaging directory
run: cp -R Source/MQTTnet.Server/bin/Release/net5.0/linux-x64/publish/* packaging/opt/MQTTnetServer
- name: Adjust files
run: |
rm packaging/opt/MQTTnetServer/appsettings.Development.json
mv packaging/opt/MQTTnetServer/appsettings.json packaging/opt/MQTTnetServer/appsettings.template.json
- name: Adjust permissions
run: |
cd packaging/opt/MQTTnetServer
find . -type f | xargs chmod -R 644
chmod 755 MQTTnet.Server
- name: Generate MD5s
run: |
cd packaging/
md5sum $(find * -type f -not -path 'DEBIAN/*') > DEBIAN/md5sums
- name: Patch meta
run: sed -i 's/\VERSIONPLACEHOLDER/${{ env.VERSION }}/' packaging/DEBIAN/control
- name: Package everything
run: dpkg-deb -v --build packaging/ mqttnet-server_${{ env.VERSION }}-1_amd64.deb
- name: Save artifact
uses: actions/upload-artifact@v2
with:
name: mqttnet-server
path: mqttnet-server_${{ env.VERSION }}-1_amd64.deb
+5 -5
View File
@@ -12,11 +12,11 @@
<requireLicenseAcceptance>true</requireLicenseAcceptance>
<description>MQTTnet is a high performance .NET library for MQTT based communication. It provides a MQTT client and a MQTT server (broker) and supports v3.1.0, v3.1.1 and v5.0.0 of the MQTT protocol.</description>
<releaseNotes>
* [Core] Removed IDisposable from MqttClientConnection.cs (#1284).
* [Core] Improved message of timeout exception (#1302, thanks to @patagonaa).
* [RpcClient] Filling response topic when using MQTTv5. (#1295, thanks to @MD-V).
* [Server] Fixed 'SessionIsPresent' handling for MQTTv5 (#1300, thanks to @logicaloud).
* [Server] Improved session management for MQTTv5 (#1294, thanks to @logicaloud).
* [Client] Increased delay for keep alive checks do decrease CPU load.
* [Core] Decreased object allocations (#1324, thanks to @gfoidl).
* [Core] Decreased object allocations when logging is not active (thanks to @gfoidl, @Tymoniden).
* [Client] Fixed issue in _MqttApplicationMessageBuilder.WithPayload_ (#1322, thanks to @gfoidl).
Git commit: $gitCommit
</releaseNotes>
<copyright>Copyright Christian Kratky 2016-2021</copyright>
+3 -2
View File
@@ -5,6 +5,7 @@ if ([string]::IsNullOrEmpty($nugetVersion)) {$nugetVersion = "0.0.1"}
$vswhere = ${Env:\ProgramFiles(x86)} + '\Microsoft Visual Studio\Installer\vswhere'
$msbuild = &$vswhere -products * -requires Microsoft.Component.MSBuild -latest -find MSBuild\**\Bin\MSBuild.exe
$vstest = &$vswhere -products * -latest -find **\TestWindow\**\vstest.console.exe
Write-Host
Write-Host "Assembly version = $assemblyVersion"
@@ -20,8 +21,8 @@ Invoke-WebRequest -Uri "https://dist.nuget.org/win-x86-commandline/latest/nuget.
&$msbuild ..\Tests\MQTTnet.Core.Tests\MQTTnet.Tests.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netcoreapp3.1" /verbosity:m
&$msbuild ..\Tests\MQTTnet.AspNetCore.Tests\MQTTnet.AspNetCore.Tests.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="netcoreapp3.1" /verbosity:m
vstest.console.exe ..\Tests\MQTTnet.Core.Tests\bin\Release\netcoreapp3.1\MQTTnet.Tests.dll
vstest.console.exe ..\Tests\MQTTnet.AspNetCore.Tests\bin\Release\netcoreapp3.1\MQTTnet.AspNetCore.Tests.dll
&$vstest ..\Tests\MQTTnet.Core.Tests\bin\Release\netcoreapp3.1\MQTTnet.Tests.dll
&$vstest ..\Tests\MQTTnet.AspNetCore.Tests\bin\Release\netcoreapp3.1\MQTTnet.AspNetCore.Tests.dll
# Build the core library
&$msbuild ..\Source\MQTTnet\MQTTnet.csproj /t:Build /p:Configuration="Release" /p:TargetFramework="net452" /p:FileVersion=$assemblyVersion /p:AssemblyVersion=$assemblyVersion /verbosity:m /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=".\..\..\Build\codeSigningKey.pfx"
-10
View File
@@ -1,10 +0,0 @@
Package: mqttnet-server
Version: VERSIONPLACEHOLDER
Section: base
Priority: optional
Architecture: amd64
Depends: libssl1.1
Suggests:
Maintainer: Damian Wolgast <packages@asymetrixs.net>
Description:
MQTTnet Server is a standalone cross platform MQTT server (like mosquitto) basing on this library.
-26
View File
@@ -1,26 +0,0 @@
The source of MQTTnet is at:
https://github.com/chkr1011/MQTTnet
Project is maintained by Christian Kratky
MIT License
Copyright (c) 2021 Damian Wolgast
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-44
View File
@@ -1,44 +0,0 @@
#!/bin/bash
# Check if user exits
USER=mqttnetsrv
USEREXISTS=$(id -u $USER >/dev/null 2>&1; echo $?)
EC=0
BASEPATH=/opt
INSTALLPATH=$BASEPATH/MQTTnetServer
# If user does not exist, create it
if (( $USEREXISTS == 1 )); then
useradd -d $INSTALLPATH -r $USER
EC=$(echo $?)
if (( $EC == 1 )); then
exit 1;
fi
fi
# Set permissions on files
chown -R root:root $INSTALLPATH
# Check if config does not exist and create it
if [ ! -f "$INSTALLPATH/appsettings.json" ]; then
cp $INSTALLPATH/appsettings.template.json $INSTALLPATH/appsettings.json
fi
# Check if setcap exists, does not exist in docker containers
SCAP=$(which setcap >/dev/null; echo $?)
if [ "$SCAP" -eq "0" ]; then
# Enable MQTTServer.NET to bind to IP interface
setcap CAP_NET_BIND_SERVICE=+eip $INSTALLPATH/MQTTnet.Server
fi
chmod 644 /etc/systemd/system/mqttnet-server.service
# Check if systemctl exists, does not exist in docker containers
SCTL=$(which systemctl >/dev/null; echo $?)
if [ "$SCTL" -eq "0" ]; then
# Reload systemd because of new service file
systemctl daemon-reload
fi
-8
View File
@@ -1,8 +0,0 @@
#!/bin/bash
# Check if systemctl exists, does not exist in docker containers
SCTL=$(which systemctl >/dev/null; echo $?)
if [ "$SCTL" -eq "0" ]; then
# Reload systemd because of new service file
systemctl daemon-reload
fi
-18
View File
@@ -1,18 +0,0 @@
#!/bin/bash
BASEPATH=/opt
INSTALLPATH=$BASEPATH/MQTTnetServer
# Check if systemctl exists, does not exist in docker containers
SCTL=$(which systemctl >/dev/null; echo $?)
if [ "$SCTL" -eq "0" ]; then
# Stop service before uninstalling
systemctl stop mqttnet-server
fi
# Check if setcap exists, does not exist in docker containers
SCAP=$(which setcap >/dev/null; echo $?)
if [ "$SCAP" -eq "0" ]; then
# Remove permission to open ports
setcap CAP_NET_BIND_SERVICE=-eip $INSTALLPATH/MQTTnet.Server
fi
@@ -1,14 +0,0 @@
[Unit]
Description=MQTTnetServer
After=network.target
[Service]
ExecStart=/opt/MQTTnetServer/MQTTnet.Server
WorkingDirectory=/opt/MQTTnetServer
StandardOutput=inherit
StandardError=inherit
Restart=always
User=mqttnetsrv
[Install]
WantedBy=multi-user.target
+6
View File
@@ -0,0 +1,6 @@
# Code of Conduct
This project has adopted the code of conduct defined by the Contributor Covenant
to clarify expected behavior in our community.
For more information, see the [.NET Foundation Code of Conduct](https://dotnetfoundation.org/code-of-conduct).
+1 -2
View File
@@ -5,10 +5,9 @@
</p>
[![NuGet Badge](https://buildstats.info/nuget/MQTTnet)](https://www.nuget.org/packages/MQTTnet)
[![Build status](https://ci.appveyor.com/api/projects/status/ycit86voxfevm2aa/branch/master?svg=true)](https://ci.appveyor.com/project/chkr1011/mqttnet)
[![BCH compliance](https://bettercodehub.com/edge/badge/chkr1011/MQTTnet?branch=master)](https://bettercodehub.com/)
[![Join the chat at https://gitter.im/MQTTnet/community](https://badges.gitter.im/MQTTnet/community.svg)](https://gitter.im/MQTTnet/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://raw.githubusercontent.com/chkr1011/MQTTnet/master/LICENSE)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://raw.githubusercontent.com/chkr1011/MQTTnet/master/LICENSE)
# MQTTnet
+2 -2
View File
@@ -455,7 +455,7 @@ namespace MQTTnet.Client
_logger.Verbose("Start sending keep alive packets.");
var keepAlivePeriod = Options.KeepAlivePeriod;
while (!cancellationToken.IsCancellationRequested)
{
// Values described here: [MQTT-3.1.2-24].
@@ -470,7 +470,7 @@ namespace MQTTnet.Client
// due to some edge cases and was buggy in the past. Now we wait several ms because the
// min keep alive value is one second so that the server will wait 1.5 seconds for a PING
// packet.
await Task.Delay(TimeSpan.FromMilliseconds(100), cancellationToken).ConfigureAwait(false);
await Task.Delay(250, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception exception)
@@ -4,6 +4,8 @@ namespace MQTTnet.Diagnostics.Logger
{
public interface IMqttNetLogger
{
bool IsEnabled { get; }
void Publish(MqttNetLogLevel logLevel, string source, string message, object[] parameters, Exception exception);
}
}
@@ -16,6 +16,8 @@ namespace MQTTnet.Diagnostics.Logger
public string LogId { get; }
public bool IsEnabled { get; set; } = true;
public void Publish(MqttNetLogLevel level, string source, string message, object[] parameters, Exception exception)
{
var eventHandler = LogMessagePublished;
@@ -7,6 +7,8 @@ namespace MQTTnet.Diagnostics.Logger
/// </summary>
public sealed class MqttNetNullLogger : IMqttNetLogger
{
public bool IsEnabled { get; }
public void Publish(MqttNetLogLevel logLevel, string source, string message, object[] parameters, Exception exception)
{
}
@@ -13,6 +13,8 @@ namespace MQTTnet.Diagnostics.Logger
_source = source;
}
public bool IsEnabled => _logger.IsEnabled;
public void Publish(MqttNetLogLevel logLevel, string message, object[] parameters, Exception exception)
{
_logger.Publish(logLevel, _source, message, parameters, exception);
@@ -4,66 +4,176 @@ namespace MQTTnet.Diagnostics.Logger
{
public static class MqttNetSourceLoggerExtensions
{
/*
* The logger uses generic parameters in order to avoid boxing of parameter values like integers etc.
*/
public static MqttNetSourceLogger WithSource(this IMqttNetLogger logger, string source)
{
if (logger == null) throw new ArgumentNullException(nameof(logger));
return new MqttNetSourceLogger(logger, source);
}
public static void Verbose(this MqttNetSourceLogger logger, string message, params object[] parameters)
public static void Verbose<TParameter1>(this MqttNetSourceLogger logger, string message, TParameter1 parameter1)
{
logger.Publish(MqttNetLogLevel.Verbose, message, parameters, null);
if (!logger.IsEnabled)
{
return;
}
logger.Publish(MqttNetLogLevel.Verbose, message, new object[] {parameter1}, null);
}
public static void Verbose<TParameter1, TParameter2>(this MqttNetSourceLogger logger, string message, TParameter1 parameter1, TParameter2 parameter2)
{
if (!logger.IsEnabled)
{
return;
}
logger.Publish(MqttNetLogLevel.Verbose, message, new object[] {parameter1, parameter2}, null);
}
public static void Verbose<TParameter1, TParameter2, TParameter3>(this MqttNetSourceLogger logger, string message, TParameter1 parameter1, TParameter2 parameter2,
TParameter3 parameter3)
{
if (!logger.IsEnabled)
{
return;
}
logger.Publish(MqttNetLogLevel.Verbose, message, new object[] {parameter1, parameter2, parameter3}, null);
}
public static void Verbose(this MqttNetSourceLogger logger, string message)
{
if (!logger.IsEnabled)
{
return;
}
logger.Publish(MqttNetLogLevel.Verbose, message, null, null);
}
public static void Info(this MqttNetSourceLogger logger, string message, params object[] parameters)
public static void Info<TParameter1>(this MqttNetSourceLogger logger, string message, TParameter1 parameter1)
{
logger.Publish(MqttNetLogLevel.Info, message, parameters, null);
if (!logger.IsEnabled)
{
return;
}
logger.Publish(MqttNetLogLevel.Info, message, new object[] {parameter1}, null);
}
public static void Info<TParameter1, TParameter2>(this MqttNetSourceLogger logger, string message, TParameter1 parameter1, TParameter2 parameter2)
{
if (!logger.IsEnabled)
{
return;
}
logger.Publish(MqttNetLogLevel.Info, message, new object[] {parameter1, parameter2}, null);
}
public static void Info(this MqttNetSourceLogger logger, string message)
{
if (!logger.IsEnabled)
{
return;
}
logger.Publish(MqttNetLogLevel.Info, message, null, null);
}
public static void Warning(this MqttNetSourceLogger logger, Exception exception, string message, params object[] parameters)
public static void Warning<TParameter1>(this MqttNetSourceLogger logger, Exception exception, string message, TParameter1 parameter1)
{
logger.Publish(MqttNetLogLevel.Warning, message, parameters, exception);
if (!logger.IsEnabled)
{
return;
}
logger.Publish(MqttNetLogLevel.Warning, message, new object[] {parameter1}, exception);
}
public static void Warning<TParameter1, TParameter2>(this MqttNetSourceLogger logger, Exception exception, string message, TParameter1 parameter1, TParameter2 parameter2)
{
if (!logger.IsEnabled)
{
return;
}
logger.Publish(MqttNetLogLevel.Warning, message, new object[] {parameter1, parameter2}, exception);
}
public static void Warning(this MqttNetSourceLogger logger, Exception exception, string message)
{
if (!logger.IsEnabled)
{
return;
}
logger.Publish(MqttNetLogLevel.Warning, message, null, exception);
}
public static void Warning(this MqttNetSourceLogger logger, string message, params object[] parameters)
public static void Warning<TParameter1>(this MqttNetSourceLogger logger, string message, TParameter1 parameter1)
{
logger.Publish(MqttNetLogLevel.Warning, message, parameters, null);
if (!logger.IsEnabled)
{
return;
}
logger.Publish(MqttNetLogLevel.Warning, message, new object[] {parameter1}, null);
}
public static void Warning(this MqttNetSourceLogger logger, string message)
{
if (!logger.IsEnabled)
{
return;
}
logger.Publish(MqttNetLogLevel.Warning, message, null, null);
}
public static void Error(this MqttNetSourceLogger logger, Exception exception, string message, params object[] parameters)
public static void Error<TParameter1>(this MqttNetSourceLogger logger, Exception exception, string message, TParameter1 parameter1)
{
logger.Publish(MqttNetLogLevel.Error, message, parameters, exception);
if (!logger.IsEnabled)
{
return;
}
logger.Publish(MqttNetLogLevel.Error, message, new object[] {parameter1}, exception);
}
public static void Error<TParameter1, TParameter2>(this MqttNetSourceLogger logger, Exception exception, string message, TParameter1 parameter1, TParameter2 parameter2)
{
if (!logger.IsEnabled)
{
return;
}
logger.Publish(MqttNetLogLevel.Error, message, new object[] {parameter1, parameter2}, exception);
}
public static void Error(this MqttNetSourceLogger logger, Exception exception, string message)
{
if (!logger.IsEnabled)
{
return;
}
logger.Publish(MqttNetLogLevel.Error, message, null, exception);
}
public static void Error(this MqttNetSourceLogger logger, string message)
{
if (!logger.IsEnabled)
{
return;
}
logger.Publish(MqttNetLogLevel.Error, message, null, null);
}
}
}
}
@@ -1,4 +1,4 @@
using System;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
@@ -11,12 +11,14 @@ namespace MQTTnet.Implementations
public sealed class CrossPlatformSocket : IDisposable
{
readonly Socket _socket;
readonly Action _socketDisposeAction;
NetworkStream _networkStream;
public CrossPlatformSocket(AddressFamily addressFamily)
{
_socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
_socketDisposeAction = _socket.Dispose;
}
public CrossPlatformSocket()
@@ -24,12 +26,16 @@ namespace MQTTnet.Implementations
// Having this constructor is important because avoiding the address family as parameter
// will make use of dual mode in the .net framework.
_socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
_socketDisposeAction = _socket.Dispose;
}
public CrossPlatformSocket(Socket socket)
{
_socket = socket ?? throw new ArgumentNullException(nameof(socket));
_networkStream = new NetworkStream(socket, true);
_socketDisposeAction = _socket.Dispose;
}
public bool NoDelay
@@ -112,7 +118,7 @@ namespace MQTTnet.Implementations
_networkStream?.Dispose();
// Workaround for: https://github.com/dotnet/corefx/issues/24430
using (cancellationToken.Register(() => _socket.Dispose()))
using (cancellationToken.Register(_socketDisposeAction))
{
cancellationToken.ThrowIfCancellationRequested();
@@ -18,10 +18,16 @@ namespace MQTTnet.Implementations
{
readonly IMqttClientOptions _clientOptions;
readonly MqttClientTcpOptions _tcpOptions;
readonly Action _disposeAction;
Stream _stream;
public MqttTcpChannel(IMqttClientOptions clientOptions)
public MqttTcpChannel()
{
_disposeAction = Dispose;
}
public MqttTcpChannel(IMqttClientOptions clientOptions) : this()
{
_clientOptions = clientOptions ?? throw new ArgumentNullException(nameof(clientOptions));
_tcpOptions = (MqttClientTcpOptions)clientOptions.ChannelOptions;
@@ -29,7 +35,7 @@ namespace MQTTnet.Implementations
IsSecureConnection = clientOptions.ChannelOptions?.TlsOptions?.UseTls == true;
}
public MqttTcpChannel(Stream stream, string endpoint, X509Certificate2 clientCertificate)
public MqttTcpChannel(Stream stream, string endpoint, X509Certificate2 clientCertificate) : this()
{
_stream = stream ?? throw new ArgumentNullException(nameof(stream));
@@ -149,11 +155,15 @@ namespace MQTTnet.Implementations
return 0;
}
#if NETCOREAPP3_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
return await stream.ReadAsync(buffer.AsMemory(offset, count), cancellationToken).ConfigureAwait(false);
#else
// Workaround for: https://github.com/dotnet/corefx/issues/24430
using (cancellationToken.Register(Dispose))
using (cancellationToken.Register(_disposeAction))
{
return await stream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
}
#endif
}
catch (ObjectDisposedException)
{
@@ -177,18 +187,22 @@ namespace MQTTnet.Implementations
try
{
// Workaround for: https://github.com/dotnet/corefx/issues/24430
using (cancellationToken.Register(Dispose))
var stream = _stream;
if (stream == null)
{
var stream = _stream;
if (stream == null)
{
throw new MqttCommunicationException("The TCP connection is closed.");
}
throw new MqttCommunicationException("The TCP connection is closed.");
}
#if NETCOREAPP3_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
await stream.WriteAsync(buffer.AsMemory(offset, count), cancellationToken).ConfigureAwait(false);
#else
// Workaround for: https://github.com/dotnet/corefx/issues/24430
using (cancellationToken.Register(_disposeAction))
{
await stream.WriteAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
}
#endif
}
catch (ObjectDisposedException)
{
@@ -159,7 +159,18 @@ namespace MQTTnet
else
{
_payload = new byte[length];
payload.Read(_payload, 0, _payload.Length);
var totalRead = 0;
do
{
var bytesRead = payload.Read(_payload, totalRead, _payload.Length - totalRead);
if (bytesRead == 0)
{
break;
}
totalRead += bytesRead;
}
while (totalRead < length);
}
return this;
@@ -35,7 +35,7 @@ namespace MQTTnet.Tests.Logger
childLogger.Verbose("Verbose");
childLogger.Info("Info");
childLogger.Warning(null, "Warning");
childLogger.Warning((Exception)null, "Warning");
childLogger.Error(null, "Error");
Assert.AreEqual(4, logMessagesCount);
@@ -55,7 +55,7 @@ namespace MQTTnet.Tests.Logger
childLogger.Verbose("Verbose");
childLogger.Info("Info");
childLogger.Warning(null, "Warning");
childLogger.Warning((Exception)null, "Warning");
childLogger.Error(null, "Error");
}
}
@@ -18,7 +18,7 @@ namespace MQTTnet.Tests.Logger
};
var sourceLogger = logger.WithSource("The_Source");
sourceLogger.Info("MESSAGE", null, null);
sourceLogger.Info("MESSAGE", (object)null, (object)null);
Assert.AreEqual("The_Source", logMessage.Source);
}
@@ -6,7 +6,9 @@ namespace MQTTnet.Tests.Mockups
public sealed class TestLogger : IMqttNetLogger
{
public event EventHandler<MqttNetLogMessagePublishedEventArgs> LogMessagePublished;
public bool IsEnabled { get; } = true;
public void Publish(MqttNetLogLevel logLevel, string source, string message, object[] parameters, Exception exception)
{
LogMessagePublished?.Invoke(this, new MqttNetLogMessagePublishedEventArgs(new MqttNetLogMessage
+1 -1
View File
@@ -190,7 +190,7 @@ namespace MQTTnet.Tests
var responseSender = await testEnvironment.ConnectClient();
await responseSender.SubscribeAsync("MQTTnet.RPC/+/ping", MqttQualityOfServiceLevel.AtMostOnce);
responseSender.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(async e =>
responseSender.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
{
Assert.IsNull(e.ApplicationMessage.ResponseTopic);
});
@@ -94,12 +94,12 @@ namespace MQTTnet.TestApp.NetCore
.WithProtocolVersion(MqttProtocolVersion.V311).Build());
await ExecuteTestAsync("broker.emqx.io TCP TLS12",
new MqttClientOptionsBuilder().WithTcpServer("broker.emqx.io", 8083)
new MqttClientOptionsBuilder().WithTcpServer("broker.emqx.io", 8883)
.WithProtocolVersion(MqttProtocolVersion.V311).WithTls(unsafeTls12).Build());
#if NET5_0_OR_GREATER
await ExecuteTestAsync("broker.emqx.io TCP TLS13",
new MqttClientOptionsBuilder().WithTcpServer("broker.emqx.io", 8083)
new MqttClientOptionsBuilder().WithTcpServer("broker.emqx.io", 8883)
.WithProtocolVersion(MqttProtocolVersion.V311).WithTls(unsafeTls13).Build());
#endif
-1
View File
@@ -1 +0,0 @@
theme: jekyll-theme-hacker
-15
View File
@@ -1,15 +0,0 @@
version: 1.0.{build}
image: Visual Studio 2019
configuration: Release
before_build:
- cmd: >-
msbuild /t:restore MQTTnet.sln
cd Tests/MQTTnet.TestApp.AspNetCore2/
npm install
build:
project: MQTTnet.sln
verbosity: minimal