Skip to content

Commit 8089c6b

Browse files
xljiulangchkr1011
andauthored
Added EndPoint RemoteEndPoint {get;} property to channel (#2111)
* Added EndPoint RemoteEndPoint{get;} property * Reformat code * Reformat code --------- Co-authored-by: christian <[email protected]>
1 parent ef5b6c9 commit 8089c6b

20 files changed

+91
-55
lines changed

Source/MQTTnet.AspnetCore/MqttConnectionContext.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -61,21 +61,21 @@ public X509Certificate2 ClientCertificate
6161
}
6262
}
6363

64-
public string Endpoint
64+
public EndPoint RemoteEndPoint
6565
{
6666
get
6767
{
6868
// mqtt over tcp
6969
if (_connection.RemoteEndPoint != null)
7070
{
71-
return _connection.RemoteEndPoint.ToString();
71+
return _connection.RemoteEndPoint;
7272
}
7373

7474
// mqtt over websocket
7575
var httpFeature = _connection.Features.Get<IHttpConnectionFeature>();
7676
if (httpFeature?.RemoteIpAddress != null)
7777
{
78-
return new IPEndPoint(httpFeature.RemoteIpAddress, httpFeature.RemotePort).ToString();
78+
return new IPEndPoint(httpFeature.RemoteIpAddress, httpFeature.RemotePort);
7979
}
8080

8181
return null;

Source/MQTTnet.AspnetCore/MqttWebSocketServerAdapter.cs

+4-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
// See the LICENSE file in the project root for more information.
44

55
using System;
6+
using System.Net;
67
using System.Net.WebSockets;
78
using System.Threading.Tasks;
89
using Microsoft.AspNetCore.Http;
@@ -28,7 +29,8 @@ public async Task RunWebSocketConnectionAsync(WebSocket webSocket, HttpContext h
2829
{
2930
ArgumentNullException.ThrowIfNull(webSocket);
3031

31-
var endpoint = $"{httpContext.Connection.RemoteIpAddress}:{httpContext.Connection.RemotePort}";
32+
var remoteAddress = httpContext.Connection.RemoteIpAddress;
33+
var remoteEndPoint = remoteAddress == null ? null : new IPEndPoint(remoteAddress, httpContext.Connection.RemotePort);
3234

3335
var clientCertificate = await httpContext.Connection.GetClientCertificateAsync().ConfigureAwait(false);
3436
try
@@ -39,7 +41,7 @@ public async Task RunWebSocketConnectionAsync(WebSocket webSocket, HttpContext h
3941
if (clientHandler != null)
4042
{
4143
var formatter = new MqttPacketFormatterAdapter(new MqttBufferWriter(4096, 65535));
42-
var channel = new MqttWebSocketChannel(webSocket, endpoint, isSecureConnection, clientCertificate);
44+
var channel = new MqttWebSocketChannel(webSocket, remoteEndPoint, isSecureConnection, clientCertificate);
4345

4446
using (var channelAdapter = new MqttChannelAdapter(channel, formatter, _logger))
4547
{

Source/MQTTnet.Benchmarks/SerializerBenchmark.cs

+2-1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
using BenchmarkDotNet.Jobs;
1616
using MQTTnet.Diagnostics.Logger;
1717
using System.Buffers;
18+
using System.Net;
1819

1920
namespace MQTTnet.Benchmarks
2021
{
@@ -76,7 +77,7 @@ public BenchmarkMqttChannel(ArraySegment<byte> buffer)
7677
_position = _buffer.Offset;
7778
}
7879

79-
public string Endpoint { get; } = string.Empty;
80+
public EndPoint RemoteEndPoint { get; set; }
8081

8182
public bool IsSecureConnection { get; } = false;
8283

Source/MQTTnet.Server/Events/ClientConnectedEventArgs.cs

+7-3
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System;
66
using System.Collections;
77
using System.Collections.Generic;
8+
using System.Net;
89
using MQTTnet.Formatter;
910
using MQTTnet.Packets;
1011

@@ -14,11 +15,11 @@ public sealed class ClientConnectedEventArgs : EventArgs
1415
{
1516
readonly MqttConnectPacket _connectPacket;
1617

17-
public ClientConnectedEventArgs(MqttConnectPacket connectPacket, MqttProtocolVersion protocolVersion, string endpoint, IDictionary sessionItems)
18+
public ClientConnectedEventArgs(MqttConnectPacket connectPacket, MqttProtocolVersion protocolVersion, EndPoint remoteEndPoint, IDictionary sessionItems)
1819
{
1920
_connectPacket = connectPacket ?? throw new ArgumentNullException(nameof(connectPacket));
2021
ProtocolVersion = protocolVersion;
21-
Endpoint = endpoint;
22+
RemoteEndPoint = remoteEndPoint;
2223
SessionItems = sessionItems ?? throw new ArgumentNullException(nameof(sessionItems));
2324
}
2425

@@ -35,7 +36,10 @@ public ClientConnectedEventArgs(MqttConnectPacket connectPacket, MqttProtocolVer
3536
/// <summary>
3637
/// Gets the endpoint of the connected client.
3738
/// </summary>
38-
public string Endpoint { get; }
39+
public EndPoint RemoteEndPoint { get; }
40+
41+
[Obsolete("Use RemoteEndPoint instead.")]
42+
public string Endpoint => RemoteEndPoint?.ToString();
3943

4044
/// <summary>
4145
/// Gets the protocol version which is used by the connected client.

Source/MQTTnet.Server/Events/ClientDisconnectedEventArgs.cs

+7-3
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System;
66
using System.Collections;
77
using System.Collections.Generic;
8+
using System.Net;
89
using MQTTnet.Packets;
910
using MQTTnet.Protocol;
1011

@@ -18,12 +19,12 @@ public ClientDisconnectedEventArgs(
1819
string clientId,
1920
MqttDisconnectPacket disconnectPacket,
2021
MqttClientDisconnectType disconnectType,
21-
string endpoint,
22+
EndPoint remoteEndPoint,
2223
IDictionary sessionItems)
2324
{
2425
ClientId = clientId ?? throw new ArgumentNullException(nameof(clientId));
2526
DisconnectType = disconnectType;
26-
Endpoint = endpoint;
27+
RemoteEndPoint = remoteEndPoint;
2728
SessionItems = sessionItems ?? throw new ArgumentNullException(nameof(sessionItems));
2829

2930
// The DISCONNECT packet can be null in case of a non clean disconnect or session takeover.
@@ -38,7 +39,10 @@ public ClientDisconnectedEventArgs(
3839

3940
public MqttClientDisconnectType DisconnectType { get; }
4041

41-
public string Endpoint { get; }
42+
public EndPoint RemoteEndPoint { get; }
43+
44+
[Obsolete("Use RemoteEndPoint instead.")]
45+
public string Endpoint => RemoteEndPoint?.ToString();
4246

4347
/// <summary>
4448
/// Gets the reason code sent by the client.

Source/MQTTnet.Server/Events/InterceptingPacketEventArgs.cs

+7-3
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,19 @@
44

55
using System;
66
using System.Collections;
7+
using System.Net;
78
using System.Threading;
89
using MQTTnet.Packets;
910

1011
namespace MQTTnet.Server
1112
{
1213
public sealed class InterceptingPacketEventArgs : EventArgs
1314
{
14-
public InterceptingPacketEventArgs(CancellationToken cancellationToken, string clientId, string endpoint, MqttPacket packet, IDictionary sessionItems)
15+
public InterceptingPacketEventArgs(CancellationToken cancellationToken, string clientId, EndPoint remoteEndPoint, MqttPacket packet, IDictionary sessionItems)
1516
{
1617
CancellationToken = cancellationToken;
1718
ClientId = clientId ?? throw new ArgumentNullException(nameof(clientId));
18-
Endpoint = endpoint;
19+
RemoteEndPoint = remoteEndPoint;
1920
Packet = packet ?? throw new ArgumentNullException(nameof(packet));
2021
SessionItems = sessionItems;
2122
}
@@ -34,7 +35,10 @@ public InterceptingPacketEventArgs(CancellationToken cancellationToken, string c
3435
/// <summary>
3536
/// Gets the endpoint of the sending or receiving client.
3637
/// </summary>
37-
public string Endpoint { get; }
38+
public EndPoint RemoteEndPoint { get; }
39+
40+
[Obsolete("Use RemoteEndPoint instead.")]
41+
public string Endpoint => RemoteEndPoint?.ToString();
3842

3943
/// <summary>
4044
/// Gets or sets the MQTT packet which was received or will be sent.

Source/MQTTnet.Server/Events/ValidatingConnectionEventArgs.cs

+5-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System;
66
using System.Collections;
77
using System.Collections.Generic;
8+
using System.Net;
89
using System.Security.Cryptography.X509Certificates;
910
using System.Text;
1011
using MQTTnet.Adapter;
@@ -70,7 +71,10 @@ public ValidatingConnectionEventArgs(MqttConnectPacket connectPacket, IMqttChann
7071
/// </summary>
7172
public string ClientId => _connectPacket.ClientId;
7273

73-
public string Endpoint => ChannelAdapter.Endpoint;
74+
public EndPoint RemoteEndPoint => ChannelAdapter.RemoteEndPoint;
75+
76+
[Obsolete("Use RemoteEndPoint instead.")]
77+
public string Endpoint => RemoteEndPoint?.ToString();
7478

7579
public bool IsSecureConnection => ChannelAdapter.IsSecureConnection;
7680

Source/MQTTnet.Server/Internal/Adapter/MqttTcpServerListener.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -167,11 +167,11 @@ async Task AcceptClientConnectionsAsync(CancellationToken cancellationToken)
167167
async Task TryHandleClientConnectionAsync(CrossPlatformSocket clientSocket)
168168
{
169169
Stream stream = null;
170-
string remoteEndPoint = null;
170+
EndPoint remoteEndPoint = null;
171171

172172
try
173173
{
174-
remoteEndPoint = clientSocket.RemoteEndPoint.ToString();
174+
remoteEndPoint = clientSocket.RemoteEndPoint;
175175

176176
_logger.Verbose("TCP client '{0}' accepted (Local endpoint={1})", remoteEndPoint, _localEndPoint);
177177

Source/MQTTnet.Server/Internal/MqttClientSessionsManager.cs

+16-11
Original file line numberDiff line numberDiff line change
@@ -19,22 +19,18 @@ namespace MQTTnet.Server.Internal;
1919
public sealed class MqttClientSessionsManager : ISubscriptionChangedNotification, IDisposable
2020
{
2121
readonly Dictionary<string, MqttConnectedClient> _clients = new(4096);
22-
2322
readonly AsyncLock _createConnectionSyncRoot = new();
24-
2523
readonly MqttServerEventContainer _eventContainer;
2624
readonly MqttNetSourceLogger _logger;
2725
readonly MqttServerOptions _options;
28-
2926
readonly MqttRetainedMessagesManager _retainedMessagesManager;
3027
readonly IMqttNetLogger _rootLogger;
31-
3228
readonly ReaderWriterLockSlim _sessionsManagementLock = new();
3329

3430
// The _sessions dictionary contains all session, the _subscriberSessions hash set contains subscriber sessions only.
3531
// See the MqttSubscription object for a detailed explanation.
3632
readonly MqttSessionsStorage _sessionsStorage = new();
37-
readonly HashSet<MqttSession> _subscriberSessions = new();
33+
readonly HashSet<MqttSession> _subscriberSessions = [];
3834

3935
public MqttClientSessionsManager(MqttServerOptions options, MqttRetainedMessagesManager retainedMessagesManager, MqttServerEventContainer eventContainer, IMqttNetLogger logger)
4036
{
@@ -365,7 +361,11 @@ public async Task HandleClientConnectionAsync(IMqttChannelAdapter channelAdapter
365361

366362
if (_eventContainer.ClientConnectedEvent.HasHandlers)
367363
{
368-
var eventArgs = new ClientConnectedEventArgs(connectPacket, channelAdapter.PacketFormatterAdapter.ProtocolVersion, channelAdapter.Endpoint, connectedClient.Session.Items);
364+
var eventArgs = new ClientConnectedEventArgs(
365+
connectPacket,
366+
channelAdapter.PacketFormatterAdapter.ProtocolVersion,
367+
channelAdapter.RemoteEndPoint,
368+
connectedClient.Session.Items);
369369

370370
await _eventContainer.ClientConnectedEvent.TryInvokeAsync(eventArgs, _logger).ConfigureAwait(false);
371371
}
@@ -403,7 +403,7 @@ public async Task HandleClientConnectionAsync(IMqttChannelAdapter channelAdapter
403403
}
404404
}
405405

406-
var endpoint = connectedClient.Endpoint;
406+
var endpoint = connectedClient.RemoteEndPoint;
407407

408408
if (connectedClient.Id != null && !connectedClient.IsTakenOver && _eventContainer.ClientDisconnectedEvent.HasHandlers)
409409
{
@@ -591,7 +591,12 @@ async Task<MqttConnectedClient> CreateClientConnection(
591591

592592
if (_eventContainer.ClientDisconnectedEvent.HasHandlers)
593593
{
594-
var eventArgs = new ClientDisconnectedEventArgs(oldConnectedClient.Id, null, MqttClientDisconnectType.Takeover, oldConnectedClient.Endpoint, oldConnectedClient.Session.Items);
594+
var eventArgs = new ClientDisconnectedEventArgs(
595+
oldConnectedClient.Id,
596+
null,
597+
MqttClientDisconnectType.Takeover,
598+
oldConnectedClient.RemoteEndPoint,
599+
oldConnectedClient.Session.Items);
595600

596601
await _eventContainer.ClientDisconnectedEvent.TryInvokeAsync(eventArgs, _logger).ConfigureAwait(false);
597602
}
@@ -655,14 +660,14 @@ async Task<MqttConnectPacket> ReceiveConnectPacket(IMqttChannelAdapter channelAd
655660
}
656661
catch (OperationCanceledException)
657662
{
658-
_logger.Warning("Client '{0}': Connected but did not sent a CONNECT packet.", channelAdapter.Endpoint);
663+
_logger.Warning("Client '{0}': Connected but did not sent a CONNECT packet.", channelAdapter.RemoteEndPoint);
659664
}
660665
catch (MqttCommunicationTimedOutException)
661666
{
662-
_logger.Warning("Client '{0}': Connected but did not sent a CONNECT packet.", channelAdapter.Endpoint);
667+
_logger.Warning("Client '{0}': Connected but did not sent a CONNECT packet.", channelAdapter.RemoteEndPoint);
663668
}
664669

665-
_logger.Warning("Client '{0}': First received packet was no 'CONNECT' packet [MQTT-3.1.0-1].", channelAdapter.Endpoint);
670+
_logger.Warning("Client '{0}': First received packet was no 'CONNECT' packet [MQTT-3.1.0-1].", channelAdapter.RemoteEndPoint);
666671
return null;
667672
}
668673

Source/MQTTnet.Server/Internal/MqttConnectedClient.cs

+8-9
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33
// See the LICENSE file in the project root for more information.
44

5+
using System.Net;
56
using MQTTnet.Adapter;
67
using MQTTnet.Diagnostics.Logger;
78
using MQTTnet.Exceptions;
@@ -45,7 +46,7 @@ public MqttConnectedClient(
4546
ConnectPacket = connectPacket ?? throw new ArgumentNullException(nameof(connectPacket));
4647

4748
ChannelAdapter = channelAdapter ?? throw new ArgumentNullException(nameof(channelAdapter));
48-
Endpoint = channelAdapter.Endpoint;
49+
RemoteEndPoint = channelAdapter.RemoteEndPoint;
4950
Session = session ?? throw new ArgumentNullException(nameof(session));
5051

5152
ArgumentNullException.ThrowIfNull(logger);
@@ -59,14 +60,14 @@ public MqttConnectedClient(
5960

6061
public MqttDisconnectPacket DisconnectPacket { get; private set; }
6162

62-
public string Endpoint { get; }
63-
6463
public string Id => ConnectPacket.ClientId;
6564

6665
public bool IsRunning { get; private set; }
6766

6867
public bool IsTakenOver { get; set; }
6968

69+
public EndPoint RemoteEndPoint { get; }
70+
7071
public MqttSession Session { get; }
7172

7273
public MqttClientStatistics Statistics { get; } = new();
@@ -338,7 +339,7 @@ async Task<MqttPacket> InterceptPacketAsync(MqttPacket packet, CancellationToken
338339
return packet;
339340
}
340341

341-
var interceptingPacketEventArgs = new InterceptingPacketEventArgs(cancellationToken, Id, Endpoint, packet, Session.Items);
342+
var interceptingPacketEventArgs = new InterceptingPacketEventArgs(cancellationToken, Id, RemoteEndPoint, packet, Session.Items);
342343
await _eventContainer.InterceptingOutboundPacketEvent.InvokeAsync(interceptingPacketEventArgs).ConfigureAwait(false);
343344

344345
if (!interceptingPacketEventArgs.ProcessPacket || packet == null)
@@ -384,7 +385,7 @@ async Task ReceivePackagesLoop(CancellationToken cancellationToken)
384385

385386
if (_eventContainer.InterceptingInboundPacketEvent.HasHandlers)
386387
{
387-
var interceptingPacketEventArgs = new InterceptingPacketEventArgs(cancellationToken, Id, Endpoint, currentPacket, Session.Items);
388+
var interceptingPacketEventArgs = new InterceptingPacketEventArgs(cancellationToken, Id, RemoteEndPoint, currentPacket, Session.Items);
388389
await _eventContainer.InterceptingInboundPacketEvent.InvokeAsync(interceptingPacketEventArgs).ConfigureAwait(false);
389390
currentPacket = interceptingPacketEventArgs.Packet;
390391
processPacket = interceptingPacketEventArgs.ProcessPacket;
@@ -560,10 +561,8 @@ async Task TrySendDisconnectPacket(MqttServerClientDisconnectOptions options)
560561

561562
var disconnectPacket = MqttDisconnectPacketFactory.Create(options);
562563

563-
using (var timeout = new CancellationTokenSource(_serverOptions.DefaultCommunicationTimeout))
564-
{
565-
await SendPacketAsync(disconnectPacket, timeout.Token).ConfigureAwait(false);
566-
}
564+
using var timeout = new CancellationTokenSource(_serverOptions.DefaultCommunicationTimeout);
565+
await SendPacketAsync(disconnectPacket, timeout.Token).ConfigureAwait(false);
567566
}
568567
catch (Exception exception)
569568
{

Source/MQTTnet.Server/Status/MqttClientStatus.cs

+5-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
using MQTTnet.Formatter;
66
using MQTTnet.Server.Internal;
7+
using System.Net;
78

89
namespace MQTTnet.Server;
910

@@ -22,7 +23,10 @@ public MqttClientStatus(MqttConnectedClient client)
2223

2324
public DateTime ConnectedTimestamp => _client.Statistics.ConnectedTimestamp;
2425

25-
public string Endpoint => _client.Endpoint;
26+
public EndPoint RemoteEndPoint => _client.RemoteEndPoint;
27+
28+
[Obsolete("Use RemoteEndPoint instead.")]
29+
public string Endpoint => RemoteEndPoint?.ToString();
2630

2731
/// <summary>
2832
/// Gets or sets the client identifier.

Source/MQTTnet.TestApp/ServerTest.cs

+3-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,9 @@ public static async Task RunAsync()
4343
{
4444
try
4545
{
46-
var options = new MqttServerOptions();
46+
var options = new MqttServerOptionsBuilder()
47+
.WithDefaultEndpoint()
48+
.Build();
4749

4850
// Extend the timestamp for all messages from clients.
4951
// Protect several topics from being subscribed from every client.

0 commit comments

Comments
 (0)