我最近一直在使用 MQTTnet,当我尝试创建代理并使用另一个 IP(不是默认 IP,通常是
0.0.0.0
)与客户端连接到它时,我遇到了一些问题。
对于这种情况,假设我的本地 IP 是
192.168.1.56
,我希望经纪人位于 192.168.1.57
。
代理创建和运行成功,但一旦我尝试连接它,连接就会被主动拒绝。 我已经添加了防火墙规则以允许应用程序监听端口
1883
(MQTT 使用的端口)。
如您所见,我在网络方面完全是菜鸟,所以任何帮助将不胜感激。
这是我制作的代码示例:
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Server;
var mqttServerOptions = new MqttServerOptionsBuilder()
.WithDefaultEndpointBoundIPAddress(System.Net.IPAddress.Parse("192.168.1.57"))
.WithDefaultEndpointPort(1883)
.Build();
var server = new MqttFactory().CreateMqttServer(mqttServerOptions);
server.StartedAsync += async (e) =>
{
Console.WriteLine("MQTT server started.");
await Task.CompletedTask;
};
await server.StartAsync();
var factory = new MqttFactory();
var mqttClient = factory.CreateMqttClient();
var mqttClientOptions = new MqttClientOptionsBuilder()
.WithClientId("Client1")
.WithTcpServer("192.168.1.57", 1883)
.Build();
mqttClient.ConnectedAsync += async e =>
{
Console.WriteLine("Connected to MQTT broker.");
await Task.CompletedTask;
};
mqttClient.DisconnectedAsync += async e =>
{
Console.WriteLine("Disconnected from MQTT broker.");
await Task.CompletedTask;
};
await mqttClient.ConnectAsync(mqttClientOptions);
我还尝试对经纪人执行
ping
,但似乎出现了问题,因为提示说无法访问:
Ping结果
这里涉及几个因素;首先是您的服务器代码(根据问题)实际上并未侦听连接,因为它缺少
.WithDefaultEndpoint()
。如果我解决了这个问题,你的代码对我有用(客户端和服务器都使用我的机器IP)。我怀疑您的机器上正在运行另一个代理(这就是为什么当您尝试连接到 127.0.0.1
时您的代码似乎可以正常工作)。请注意,我使用的是端口 10,000(以避免出现这种情况!)。
如果我将 IP 更改为我的计算机上未配置的 IP,则会收到错误:
Unhandled exception. System.Net.Sockets.SocketException (10049): The requested address is not valid in its context.
这是预期的,因为您无法侦听未连接到计算机上的接口的地址。如果我现在添加地址(请参阅此答案了解一些所需的设置):
netsh interface ipv4 add address "interface name" 192.168.1.57 255.255.255.0
(将
interface name
替换为您的接口之一的名称;在我的例子中,它是“以太网 2”)。
在此更改之后,应用程序可以运行。请注意,完成后您可能应该删除该地址(您的 DHCP 服务器很可能将其分配给另一台计算机!)。
netsh interface ipv4 del address "interface name" 192.168.1.57 255.255.255.0
请参阅下面我使用的完整代码(我添加了一些日志记录,以便您可以看到传入的连接):
using System.Text;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Server;
using MQTTnet.Diagnostics;
var mqttServerOptions = new MqttServerOptionsBuilder()
.WithDefaultEndpointBoundIPAddress(System.Net.IPAddress.Parse("192.168.1.57"))
.WithDefaultEndpointPort(10000)
.WithDefaultEndpoint()
.Build();
var mqttEventLogger = new MqttNetEventLogger("MyCustomLogger");
mqttEventLogger.LogMessagePublished += (sender, args) =>
{
var output = new StringBuilder();
output.AppendLine($">> [{args.LogMessage.Timestamp:O}] [{args.LogMessage.ThreadId}] [{args.LogMessage.Source}] [{args.LogMessage.Level}]: {args.LogMessage.Message}");
if (args.LogMessage.Exception != null)
{
output.AppendLine(args.LogMessage.Exception.ToString());
}
Console.Write(output);
};
var server = new MqttFactory().CreateMqttServer(mqttServerOptions, mqttEventLogger);
server.StartedAsync += async (e) =>
{
Console.WriteLine("MQTT server started.");
await Task.CompletedTask;
};
server.ClientConnectedAsync += async (ClientConnectedEventArgs eventArgs) =>
{
Console.WriteLine($"Client '{eventArgs.ClientId}' connected.");
await Task.CompletedTask;
};
server.ValidatingConnectionAsync += async (ValidatingConnectionEventArgs eventArgs) =>
{
Console.WriteLine($"Client '{eventArgs.ClientId}' connected.");
await Task.CompletedTask;
};
await server.StartAsync();
var factory = new MqttFactory();
var mqttClient = factory.CreateMqttClient();
var mqttClientOptions = new MqttClientOptionsBuilder()
.WithClientId("Client1")
.WithTcpServer("192.168.1.57", 10000)
.Build();
mqttClient.ConnectedAsync += async e =>
{
Console.WriteLine("Connected to MQTT broker.");
await Task.CompletedTask;
};
mqttClient.DisconnectedAsync += async e =>
{
Console.WriteLine("Disconnected from MQTT broker.");
await Task.CompletedTask;
};
await mqttClient.ConnectAsync(mqttClientOptions);
输出:
>> [2024-06-30T05:51:25.3928051Z] [4] [MqttServerKeepAliveMonitor] [Info]: Starting keep alive monitor
>> [2024-06-30T05:51:25.3960953Z] [1] [MqttTcpServerListener] [Info]: Starting TCP listener (Endpoint=192.168.1.57:10000, TLS=False)
>> [2024-06-30T05:51:25.4057550Z] [1] [MqttTcpServerListener] [Verbose]: TCP listener started (Endpoint=192.168.1.57:10000)
>> [2024-06-30T05:51:25.4097879Z] [1] [MqttTcpServerListener] [Info]: Starting TCP listener (Endpoint=[::]:10000, TLS=False)
>> [2024-06-30T05:51:25.4102620Z] [1] [MqttTcpServerListener] [Verbose]: TCP listener started (Endpoint=[::]:10000)
MQTT server started.
>> [2024-06-30T05:51:25.4121238Z] [1] [MqttServer] [Info]: Started
>> [2024-06-30T05:51:25.4246244Z] [13] [MqttTcpServerListener] [Verbose]: TCP client '192.168.1.57:57580' accepted (Local endpoint=192.168.1.57:10000)
>> [2024-06-30T05:51:25.4312003Z] [13] [MqttChannelAdapter] [Verbose]: RX (21 bytes) <<< Connect: [ClientId=Client1] [Username=] [Password=] [KeepAlivePeriod=15] [CleanSession=True]
Client 'Client1' connected.
>> [2024-06-30T05:51:25.4333380Z] [13] [MqttClientSessionsManager] [Verbose]: Created new session for client 'Client1'
>> [2024-06-30T05:51:25.4364599Z] [13] [MqttChannelAdapter] [Verbose]: TX (4 bytes) >>> ConnAck: [ReturnCode=ConnectionAccepted] [ReasonCode=Success] [IsSessionPresent=False]
Client 'Client1' connected.
>> [2024-06-30T05:51:25.4379708Z] [13] [MqttClient] [Info]: Client 'Client1': Session started
Connected to MQTT broker.