当你需要ChatAI服务但无法魔法或没有海外手机号码时,Chat8就是你的解决方案。我们基于OpenAi开发,所有用户内容都会加密,欢迎使用!点击使用:
https://chat.chat826.com/#/register?bronk_on=375671
引入 MQTTNET
1服务端
public partial class MainWindow
{
IMqttServer server;
List<UserInstance> instances;
public MainWindow()
{
InitializeComponent();
instances = new List<UserInstance>();
}
private async void btnStart(object sender, RoutedEventArgs e)
{
var optionBuilder = new MqttServerOptionsBuilder().
WithDefaultEndpoint().WithDefaultEndpointPort(1883).WithConnectionValidator(
c =>
{
var flag = (c.Username != "" && c.Password != "") ? true : false;
if (!flag)
{
c.ReasonCode = MQTTnet.Protocol.MqttConnectReasonCode.BadUserNameOrPassword;
return;
}
c.ReasonCode = MQTTnet.Protocol.MqttConnectReasonCode.Success;
instances.Add(new UserInstance()
{
clientId = c.ClientId,
userName = c.Username,
passWord = c.Password
});
Showlog($"{DateTime.Now}:账号:{c.Username}已订阅!\r\n");
}).WithSubscriptionInterceptor(c =>
{
if (c == null) return;
c.AcceptSubscription = true;
Showlog($"{DateTime.Now}:订阅者{c.ClientId}\r\n");
}).WithApplicationMessageInterceptor(c =>
{
if (c == null) return;
c.AcceptPublish = true;
string str = c.ApplicationMessage?.Payload == null ? null : Encoding.UTF8.GetString(c.ApplicationMessage?.Payload) + "\r\n";
Showlog($"{DateTime.Now}:{str}\r\n");
})
;
server = new MqttFactory().CreateMqttServer();
server.UseClientDisconnectedHandler(c =>
{
var use = instances.FirstOrDefault(t => t.clientId == c.ClientId);
if (use != null)
{
instances.Remove(use);
Showlog($"{DateTime.Now}:订阅者{use.userName}已退出\r\n");
}
});
await server.StartAsync(optionBuilder.Build());
}
private void brnSend(object sender, RoutedEventArgs e)
{
instances.ForEach(arg =>
{
server.PublishAsync(new MqttApplicationMessage()
{
Topic = arg.clientId,
QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce,
Retain = false,
Payload = Encoding.UTF8.GetBytes($"{DateTime.Now}:服务器:明天都不要来上班了!")
}); ;
});
}
//更新文本框
private void Showlog(string str)
{
this.Dispatcher.Invoke(() =>
{
txtResult.Text += str;
});
}
}
2客户端
/// <summary>
///
/// </summary>
public partial class MainWindow
{
IMqttClient client;
string clientId = "";
public MainWindow()
{
InitializeComponent();
}
private async void btnStart(object sender, RoutedEventArgs e)
{
clientId = Guid.NewGuid().ToString();
var options = new MqttClientOptionsBuilder().WithTcpServer("127.0.0.1", 1883)
.WithClientId(clientId).WithCredentials("admin", "123").Build();
client = new MqttFactory().CreateMqttClient();
client.UseConnectedHandler(async c =>
{
//订阅服务端消息
await client.SubscribeAsync(new TopicFilterBuilder().WithTopic(clientId).Build());
}).UseDisconnectedHandler(c =>
{
Showlog(c.Exception.Message);
}).UseApplicationMessageReceivedHandler(c =>
{
string str = Encoding.UTF8.GetString(c.ApplicationMessage.Payload);
Showlog(str);
});
await client.ConnectAsync(options);
}
/// <summary>
/// 引入 MQTTnet.Extensions.ManagedClient
// 无论是对于Client还是Server层, 它们都有各自的其它配置, 包括一些基本的设置, 如连接成功事件、断开事件等等。
// 对于Client而言, MQTTNet还提供了一个标准的封装库, 它包含了一些常用的功能, 开箱即用。
// 托管客户端启动一次,将自动保持连接,包括重新连接等。
// 所有 MQTT 应用程序消息都被添加到内部队列中,并在服务器可用时进行处理。
// 可以存储所有 MQTT 应用程序消息,以支持在应用程序重启后发送它们
// 所有订阅都通过服务器连接进行管理。 与服务器断开连接后无需手动订阅。
// 以下代码显示了如何设置和启动托管 MQTT 客户端
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async Task btnstart2()
{
var options = new ManagedMqttClientOptionsBuilder()
.WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
.WithClientOptions(new MqttClientOptionsBuilder()
.WithClientId("clientId")
.WithTcpServer("127.0.0.1", 1883)
.WithTls().Build())
.Build();
var mqttClient = new MqttFactory().CreateManagedMqttClient();
await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("my/topic").WithTopic("多个主题").Build());
await mqttClient.StartAsync(options);
}
private void brnSend(object sender, RoutedEventArgs e)
{
var msg = new MqttApplicationMessageBuilder().
WithTopic("MyTopic").
WithPayload($"{DateTime.Now}:Hello World")
.WithExactlyOnceQoS().
WithRetainFlag().
Build(); ;
client.PublishAsync(msg);
}
private void Showlog(string str)
{
this.Dispatcher.Invoke(() =>
{
txtResult.Text += str;
});
}
}